反射

来源:互联网 发布:最好的直通车软件 编辑:程序博客网 时间:2024/06/15 13:05

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class fanshe {
public static void main(String[] args) {
try {
Class c = Class.forName("User");//获取类
Object o = c.newInstance();//实例化这个类赋给o
Field id = c.getDeclaredField("id");//获取id属性
id.setAccessible(true);//打破封装
id.set(o, 111);//给o对象id属性赋值
System.out.println("id====="+id.get(o));//get结果
Class cls[] = new Class[2];
cls[0] = int.class;
cls[1] = int.class;
Method method2 = c.getDeclaredMethod("setId",cls);//方法名称和参数类型
Method method = c.getDeclaredMethod("setId",int.class,int.class);//方法名称和参数类型
System.out.println("Method ===="+method);
method.setAccessible(true);
method.invoke(o, 100,101);//invoke获取指定方法的返回值


Method method1 = c.getDeclaredMethod("getId", null);//没有参数的方法
method1.setAccessible(true);
System.out.println("===="+method1.invoke(o));
} catch (Exception e) {
e.printStackTrace();

}
}
class User{
private int id;
private String name;
private int getId() {
return id;
}
private void setId(int id,int name) {
System.out.println("今天天气真好啊"+id+name);;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}

0 0