Java基础--反射Reflection

Reflection

反射能在运行时获取一个类的全部信息,并且可以调用类方法,修改类属性,创建类实例。

而在编译期间不用关心对象是谁

反射可用在动态代理,注解解释,和反射工厂等地方。

---------------------

public class BasicTest {

    public static void main(String[] args) throws Exception {

        Demo demo = new Demo(10,"moss");

        // 所有类的对象都是Class的实例
        Class<?> clazz = null;
        Class<?> clazz2 = null;

        //获取类对象
        clazz = Class.forName("demos.reflection.Demo");
        clazz2 = Demo.class;
        clazz2 = demo.getClass();
        Q.p(clazz.getClass());
        Q.p(clazz==clazz2);

        // 使用默认构造函数 创建一个新的实例  
        demo = (Demo) clazz.newInstance();
        demo.me();
        
        //获取所有public的构造函数
        Constructor<?>[] con =clazz2.getConstructors(); 
        Q.pl(con);
        
        //使用自定义构造函数 创建一个新的实例  
        demo=(Demo) con[1].newInstance(100,"jack");
        demo.me();
        
        //获取超类 接口
        Q.p(clazz.getSuperclass());
        Q.pl(clazz.getInterfaces());
        
        //获取所有属性,不包括继承的
        Field[] fields = clazz.getDeclaredFields();
        Q.pl(fields);
        
        //获取无参函数,调用无参函数
        Method method=clazz.getMethod("me");
        Q.p("method "+method);
        method.invoke(clazz.newInstance());
        
        //获取有参函数,调用有参函数 
        method = clazz.getDeclaredMethod("you", int.class,String.class);
        Q.p("method2 "+method);
        method.invoke(clazz.newInstance(), 19, "you");
        
        //获取所有方法,不包括父类的, 可通过getMethods()获取全部的
        Method[] methods = clazz.getDeclaredMethods();
        Q.pl(methods);
        
        //给属性赋值
        Field field = clazz.getDeclaredField("name");
        field.setAccessible(true);
        field.set(demo, "reSetName");
        Q.p(demo.getName());
        
        //获取注解
        method = clazz.getMethod("toString");
        Annotation[] as = method.getDeclaredAnnotations();
        Q.pl(as);
    }
}
class Father{
    protected String father;
}

interface Interface{}

public class Demo extends Father implements Interface{
    
    private static String k = "k";
    
    private Integer id;
    
    private String name;
    
    Demo(){}
    
    public Demo(String name){
        this.name=name;
    }
    
    public Demo(int id, String name){
        this.id=id;
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public void me() {
        Q.p("["+id+"----"+name+"]");
    }
    
    public void you(int id, String name){
        Q.p("["+id+"----"+name+"]");
    }
    
    @Override
    public String toString(){
        return "["+id+"----"+name+"]";
    }
    
}

---------------------

end 

原文地址:https://www.cnblogs.com/luangeng/p/6032011.html