---测试类
package com.test.jse.invoke;
public class MyClass {
public String n = "MyClass公有变量";
private String m = "MyClass私有变量";
public MyClass(){
System.out.println("MyClass无参公有构造方法");
}
private MyClass(int n,String name){
System.out.println("MyClass有参私有构造方法"+"\t名字:"+name+"\t编号:"+n);
}
public void say(){
System.out.println("MyClass类的无参公有一般方法---say()");
}
private void tell(String name){
System.out.println("MyClass类的一般有参私有方法----private tell()");
}
}
----利用反射获取类中属性和调用类中的方法
package com.test.jse.invoke;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class People {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.test.jse.invoke.MyClass");//反射出来的类clazz
MyClass myClass =(MyClass)clazz.newInstance();//MyClass类无参数公有构造函数
Constructor constructor = clazz.getDeclaredConstructor(new Class[]{int.class,String.class});
constructor.setAccessible(true);//设置查看私有方法的权限
MyClass myclass2 = (MyClass)constructor.newInstance(1,"张三");
System.out.println(clazz.getField("n").get(myClass));
Field field = clazz.getDeclaredField("m");//定义m变量
field.setAccessible(true);
System.out.println(field.get(myClass));
Method method_say = clazz.getMethod("say"); //先查询定位到公有say()方法
method_say.invoke(myClass);//再执行say()方法
Method method = clazz.getDeclaredMethod("tell", new Class[]{String.class }); //定义方法属性
method.setAccessible(true);
method.invoke(myClass,"张三");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
分享到:
2015-01-09 11:12
浏览 2576
评论