码迷,mamicode.com
首页 > 编程语言 > 详细

Java反射

时间:2019-07-22 21:26:23      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:declared   not   sse   nbsp   test   实现   chm   com   集成   

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

 

Java反射

标签:declared   not   sse   nbsp   test   实现   chm   com   集成   

原文地址:https://www.cnblogs.com/starstarstar/p/11228454.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!