JVM(四),什么是反射

四、什么是反射

1.反射理论

 

2.反射实践

(1)创建Robot

public class Robot {
    private String name;
    public void sayHi(String helloSentence){
        System.out.println(helloSentence + " " + name);
    }
    private String throwHello(String tag){
        return "Hello " + tag;
    }
    static {
        System.out.println("Hello Robot");
    }
}

 (2)各种操作

public class ReflectSample {
    public static void main(String[] args) throws Exception{
        Class rc = Class.forName("com.interview.javabasic.reflect.Robot");
        Robot r = (Robot) rc.newInstance();
        System.out.println("Class name is " + rc.getName());

        //调用私有方法rc.getDeclaredMethod
        Method getHello = rc.getDeclaredMethod("throwHello", String.class);
        getHello.setAccessible(true);
        Object str = getHello.invoke(r, "Bob");
        System.out.println("getHello result is " + str);

        //调用PUBLIC方法rc.getMethod
        Method sayHi = rc.getMethod("sayHi", String.class);
        sayHi.invoke(r, "Welcome");

        //设置私有属性
        Field name = rc.getDeclaredField("name");
        name.setAccessible(true);
        name.set(r, "Alice");
        sayHi.invoke(r, "Welcome");

    }
}

猜你喜欢

转载自www.cnblogs.com/xzmxddx/p/10366867.html
今日推荐