反射
| package model; |
| |
| import java.lang.reflect.*; |
| import java.util.Date; |
| |
| public class Person { |
| public static void main(String[] args) throws Exception { |
| Class personClass = Person.class; |
| Object instance = personClass.newInstance(); |
| |
| System.out.println("*****************获取公有、无参的构造方法*************"); |
| Constructor con = personClass.getConstructor(null); |
| |
| |
| |
| System.out.println("*************获取公有字段**并调用*****************"); |
| Field f = personClass.getField("age"); |
| System.out.println(f); |
| |
| |
| System.out.println("*************获取公有方法并调用*****************"); |
| Method m2 = personClass.getMethod("sayHello2", String.class); |
| Object invoke = m2.invoke(instance, new String[]{" aaa"}); |
| System.out.println(invoke); |
| |
| System.out.println("***************获取私有的方法******************"); |
| Method m3 = personClass.getDeclaredMethod("sayHello3", String.class); |
| m3.setAccessible(true); |
| Object invoke1 = m3.invoke(instance, new String[]{"vvv"}); |
| System.out.println(invoke1); |
| } |
| |
| private Integer id; |
| private String name; |
| private Integer sex; |
| private Date birth; |
| public int age; |
| |
| public Person() { |
| } |
| |
| public Person(Integer id, String name, Integer sex, Date birth, int age) { |
| this.id = id; |
| this.name = name; |
| this.sex = sex; |
| this.birth = birth; |
| this.age = age; |
| } |
| |
| public Integer getId() { |
| return id; |
| } |
| |
| public void setId(Integer id) { |
| this.id = id; |
| } |
| |
| public String getName() { |
| return name; |
| } |
| |
| public void setName(String name) { |
| this.name = name; |
| } |
| |
| public Integer getSex() { |
| return sex; |
| } |
| |
| public void setSex(Integer sex) { |
| this.sex = sex; |
| } |
| |
| public Date getBirth() { |
| return birth; |
| } |
| |
| public void setBirth(Date birth) { |
| this.birth = birth; |
| } |
| |
| public int getAge() { |
| return age; |
| } |
| |
| public void setAge(int age) { |
| this.age = age; |
| } |
| |
| public void sayHello() { |
| System.out.println("hello"); |
| } |
| |
| public String sayHello2(String name) { |
| return "hello" + name; |
| } |
| |
| private String sayHello3(String name) { |
| return "hello " + name; |
| } |
| |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了