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
    
  • 相关阅读:
    Ubuntu16.04更新记
    「BZOJ2153」设计铁路
    [UVA-11995]I Can Guess the Data Structure!
    [UVA-11100] The Trip
    [UVA-11039]Children's Game
    [BZOJ1008][HNOI2008]越狱
    NOIP2018退役祭
    修马路
    [NOIP2005]过河
    [POJ1958][Strange Tower of Hanoi]
  • 原文地址:https://www.cnblogs.com/starstarstar/p/11228454.html
Copyright © 2011-2022 走看看