获取类的运行时结构、获取类信息

//获得类信息
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
        Class c1 = Class.forName("comm.bin.User");
        
        User user = new User();

        //获得类的名字
        System.out.println(c1.getName());//获得包名+类名
        System.out.println(c1.getSimpleName());//获得类名
        
        //获得类的属性
        Field[] fields = c1.getFields();//只能找到public 属性
        for (Field field : fields) {
            System.out.println(field);
        }
        fields  = c1.getDeclaredFields();//可以找到任何属性的
        for (Field field : fields) {
            System.out.println(field);
        }
        
        //获得类的方法
        Method[] methods = c1.getMethods();//获得本类及父类的public方法
        for (Method method : methods) {
            System.out.println(method);
        }
        
        methods = c1.getDeclaredMethods();//获得本类的所有方法,
        for (Method method : methods) {
            System.out.println(methods);
        }
        
        //获得指定类的方法
        Method getName = c1.getMethod("getName",null);
        Method setName = c1.getMethod("setName",String.class);
        
        //获取指定构造器
        Constructor[] constructors = c1.getConstructors();//public
        
        constructors = c1.getDeclaredConstructors();//所有的
        
        //获得指定的构造器
        Constructor constructor = c1.getConstructor(String.class,int.class,int.class);
        
    }
}

获取类结构

获取类信息

//获得类信息
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
       //获得Class对象
        Class c1 = Class.forName("coom.bin.User");
        //构造一个对象
        Object o = c1.newInstance();//本质是调用了无参构造器
        //通过构造器构造对象
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user = (User)declaredConstructor.newInstance("qin", 20, 20);
        //通过反射调用普通方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user,"hanbin");//invoke()激活的意思(“对象”,方法)
        //通过反射操作属性
        User user1 =(User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //不能直接操作私有属性,我们需要关闭程序的安全检测setAccessible(true);
        name.setAccessible(true);
        name.set(user1,"hanbin");
        System.out.println(user1.getName());
    }

你可能感兴趣的:(java,开发语言)