获取类的运行结构
获取类的运行结构
- 类的名字、属性
- 指定类的名字、属性
- public的方法、自己全部的方法
- 指定的public的方法、自己全部的方法
- public的构造器、自己全部的构造器
- 指定的public的构造器、自己全部的构造器
运行速度比较
- 普通调用速度 > 关闭检测,反射调用速度 > 反射调用速度
代码
package reflection.Demo04;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Demo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("reflection.User");
//获取类的名字
System.out.println(c1.getName()); //包名+类名
System.out.println(c1.getSimpleName()); //获得类名
//获得类的属性
System.out.println("=================================");
Field[] fields = c1.getFields();//只能找到public属性
for (Field field : fields) {
System.out.println(field);
}
System.out.println("=================================");
fields = c1.getDeclaredFields();//找到全部属性
for (Field field : fields) {
System.out.println(field);
}
//获得指定的属性的值
System.out.println("=================================");
Field name = c1.getDeclaredField("id");
System.out.println(name);
//获取方法
System.out.println("=================================");
//获得public属性方法包括父类
Method[] method = c1.getMethods();
for (Method method1 : method) {
System.out.println("正常的" + method1);
}
//自己所有方法
System.out.println("=================================");
method = c1.getDeclaredMethods();
for (Method method1 : method) {
System.out.println("自己的" + method1);
}
//获得指定方法
//方法重载,需要注意参数
System.out.println("=================================");
Method method2 =c1.getMethod("setAge", int.class);
Method method3 =c1.getMethod("getAge",null);
System.out.println(method2);
System.out.println(method3);
//获得构造器
System.out.println("=================================");
//公共构造器
Constructor[] constructors =c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println("公共"+constructor);
}
//自己的全部构造器
constructors =c1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println("全部"+constructor);
}
//获得指定的构造器
Constructor constructor= c1.getDeclaredConstructor(String.class,int.class,int.class);
System.out.println("指定"+constructor);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义