Method add=clazz.getMethod("add", new Class[]{Integer.class,Integer.class});
add.invoke(o, new Object[]{new Integer(1),new Integer(1)});
Field i=clazz.getDeclaredField("i");//对私有的处理
i.setAccessible(true);//对私有的处理
i.get(o);
i.set(o, 2);
//Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,
//如果参数为基本类型数据,必须转换为相应的包装类型的对象。
//invoke()方法的返回值总是对象,
//如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,
class MyClass{
private Integer i = 12;
public static String s = "ss";
private String s1 = "";
private double d = 2.3;
public MyClass() {
}
public MyClass(String s1, Double d) {
this.s1 = s1;
this.d = d;
}
public int add(Integer numberA, Integer numberB) {
return numberA + numberB;
}
public static String addString(String s1, String s2) {
return s2 + "_" + s1;
}
}
public class Test {
public static void main(String args[]) throws ClassNotFoundException, SecurityException, NoSuchFieldException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
Class clazz = MyClass.class;
//Class clazz=实例.getClass();
//Class clazz=Class("包名.类名");
//静属性方法
//获得
Field static_s=clazz.getField("s");
Method static_addString=clazz.getMethod("addString", new Class[]{String.class,String.class});
//使用
static_s.set(null, "aa");
static_s.get(null);
static_addString.invoke(null, new Object[]{"wen","zong"});
//////////////////////////////////////////////////////////////////////////////////////////
//普通属性方法
//获得
Field i=clazz.getDeclaredField("i");//对私有的处理
Method add=clazz.getMethod("add", new Class[]{Integer.class,Integer.class});
//生成对象
//Object o=clazz.newInstance();无参数时
Constructor cst=clazz.getConstructor(new Class[]{String.class,Double.class});
Object o =cst.newInstance(new Object[]{"s1",new Double(10)});
//使用
i.setAccessible(true);//对私有的处理
i.get(o);
i.set(o, 2);
add.invoke(o, new Object[]{new Integer(1),new Integer(1)});
/////////////////////////////////////////////////////////////////////////////////////////////
//验证
System.out.println(static_s.get(null));//aa
System.out.println(static_addString.invoke(null, new Object[]{"wen","zong"}));//wen_zong
System.out.println(i.get(o));//2
System.out.println(add.invoke(o, new Object[]{new Integer(1),new Integer(1)}));//2
}
}