您的位置:首页 > 其它

28-反射机制-06-反射机制(获取Class中的方法)

2015-08-11 17:45 176 查看
package bean;

public class Person {

private int age;
private String name;

public Person() {
super();
System.out.println("...Person run...");

}

public Person(String name, int age) {
super();
this.age = age;
this.name = name;
System.out.println("...Person param run..." + this.name + ":"
+ this.age);
}

public void show() {

System.out.println(name + "...show run..." + age);

}

public void method() {

System.out.println("...method run...");

}

public void paramMethod(String str, int num) {

System.out.println("...paramMethod..." + str + ":" + num);

}

public static void staticMethod() {

System.out.println("...staticMethod run...");

}
}

============================分割线===============================

/*
* 获取Class中的方法,利用Class类内特有方法:
*
* (1)public Method getMethod(String name,Class<?>... parameterTypes)throws NoSuchMethodException,SecurityException
* 获取带有指定参数的共有方法
*
* (2)public Method[] getMethods() throws SecurityException
* 获取Class中所有共有方法,【注意】可以获取父类方法
*
* (3)public Method getDeclaredMethod(String name,Class<?>... parameterTypes)throws NoSuchMethodException,SecurityException
* 获取带有指定参数的方法,可以获取私有方法,【注意】获取私有方法之前先“暴力访问”去除权限(详见前一视频)
*
* (4)public Method[] getDeclaredMethods() throws SecurityException
* 获取Class中所有方法,哪怕私有的也可以获取,【注意】只能获取本类方法
*
*/

package demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Demo {

public static void main(String[] args) throws Exception {

//		getMethodDemo();
//		getMethodDemo_2();
getMethodDemo_3();

}

public static void getMethodDemo() throws Exception {//获取所有方法

Class clazz = Class.forName("bean.Person");

//获取Person及其父类所有共有方法
Method[] methods = clazz.getMethods();

for(Method method : methods){

System.out.println(method);

}

//获取Person类所有(包括私有)方法
Method[] methods1 = clazz.getDeclaredMethods();

for(Method method : methods1){

System.out.println(method);

}
}

public static void getMethodDemo_2() throws Exception{//获取指定方法名的方法,其参数为空

Class clazz = Class.forName("bean.Person");

Method method = clazz.getMethod("show", null);//获取空参数一般方法

/*
* 【思考】如何让这个方法运行?
* 如以下代码:
* 			Person p = new Person();
* 			p.show();
* 可见方法运行需要两个要素,一个是对象(如p),一个是参数(这里是空参)
*/
//以下两行代码作用是新建对象
Constructor constructor = clazz.getConstructor(String.class,int.class);

Object obj = constructor.newInstance("小明",1);

method.invoke(obj, null);//invoke()是Method类内特有的,用于运行获取到的方法

}

public static void getMethodDemo_3() throws Exception {//获取指定方法名的方法,并在方法运行时指定参数

Class clazz = Class.forName("bean.Person");

Method method = clazz.getMethod("paramMethod", String.class,int.class);

Object obj = clazz.newInstance();

method.invoke(obj, "小强",0);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: