反射的部分

2019-10-28  本文已影响0人  一起走天下
    public static void main(String[] args) {            
        try {
            Class clazz = Class.forName(Student.class.getName());
//          获取无参构造方法对象
            Constructor constructor  = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
//         通过无参构造方法对象创建对象
            Object obj = constructor.newInstance();
            System.out.println(obj);
//          通过反射给所有成员变量赋值
//          System.out.println("****通过反射给所有成员变量赋值****");
//          // private String name;
            Field nameField = clazz.getDeclaredField("name");
            nameField.setAccessible(true);
            nameField.set(obj, "风清杨");
            System.out.println(obj);
//          // int age;
            Field ageField = clazz.getDeclaredField("age");
            ageField.setAccessible(true);
            ageField.set(obj, 27);
            System.out.println(obj);


//          通过反射给所有构造方法赋值
            Constructor constructor2 = clazz.getDeclaredConstructor(String.class,int.class);
            constructor2.setAccessible(true);
            Object obj1 = constructor2.newInstance("张三丰",28);
            System.out.println(obj1);
            
            //反射调用方法
            Method method1 = clazz.getDeclaredMethod("getValue",String.class);
            method1.setAccessible(true);
            method1.invoke(obj, "uabhj");
            
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (SecurityException e) {             
                e.printStackTrace();
            } catch (ClassNotFoundException e) {                
                e.printStackTrace();
            } catch (InstantiationException e) {                
                e.printStackTrace();
            } catch (IllegalAccessException e) {                
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
    }

public class Student {
    
    private String name;
    
    public int age;
    
    private Student() {}
    
    private Student(String name,int age) {
        this.name = name;
        this.age = age;
    }
    
    private void getValue(String a) {
        System.out.println(a);
        System.out.println(name+"\t"+age);
    }
}
上一篇下一篇

猜你喜欢

热点阅读