Java反射

Java的反射:

Robot.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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");
 
    }
}

 运行结果:

1
2
3
4
class name is :qihoo.qtest.mqtt.reflect.Robot
getHello result is :private Hello:bob
welcome:null
welcome:Alace

 

posted @   豆芽花花儿酱  阅读(102)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示