zoukankan      html  css  js  c++  java
  • Java反射

    Java的反射:

    Robot.java:

    package 包.reflect;
    
    public class Robot {
        private String name;
    
        public void sayHi(String helloSen) {
            System.out.println(helloSen + ":" + name);
        }
    
        private String throwHello(String tag) {
            return "private Hello:" + tag;
        }
    }
    

     ReflectDemo.java:

    package 包.reflect;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class ReflectDemo {
        public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
            Class rc = Class.forName("包.reflect.Robot");
            Robot r = (Robot) rc.newInstance();
            System.out.println("class name is :" + rc.getName());
            // 获取声明的方法
            // getDeclaredMethod获取不到:继承的方法和实现接口的方法
            Method getPrivateHello = rc.getDeclaredMethod("throwHello", String.class);
            getPrivateHello.setAccessible(true);
            Object str = getPrivateHello.invoke(r, "bob");
            System.out.println("getHello result is :" + str);
            // getMethod获取 类自己的public方法,集成类的方法和实现接口的方法
            Method sayHi = rc.getMethod("sayHi", String.class);
            sayHi.invoke(r, "welcome");
            // 设置name
            Field name = rc.getDeclaredField("name");
            name.setAccessible(true);
            name.set(r, "Alace");
            sayHi.invoke(r, "welcome");
    
        }
    }
    

     运行结果:

    class name is :qihoo.qtest.mqtt.reflect.Robot
    getHello result is :private Hello:bob
    welcome:null
    welcome:Alace
    
  • 相关阅读:
    [HNOI2002]营业额统计 (Splay)
    [POJ1664] 放苹果 (动态规划,组合数学)
    [AHOI2009]维护序列 (线段树)
    类型转换求和
    懒人创造方法
    编程的精义
    10-instanceof
    9-接口
    6-SUPER关键字
    5-重写与重载
  • 原文地址:https://www.cnblogs.com/starstarstar/p/11228454.html
Copyright © 2011-2022 走看看