zoukankan      html  css  js  c++  java
  • 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");
    
        }
    }
  • 相关阅读:
    redis主从架构
    redis持久化
    git 首次push失败
    Java8 CompletableFuture
    Mac Item2自动远程连接服务器
    Java8 日期和时间类
    【LeetCode】31. 下一个排列
    【LeetCode】30. 串联所有单词的子串
    【LeetCode】29. 两数相除
    【LeetCode】28. 实现 strStr()
  • 原文地址:https://www.cnblogs.com/xzmxddx/p/10366867.html
Copyright © 2011-2022 走看看