反射1 - 基础
反射
对象获取自身的类对象
再通过类对象获取类中的属性、方法、权限等
public class _Reflect {
public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
User user = new Child();
user.test1();
//TODO .getClass() 获取对象的类对象
Class<? extends User> aClass = user.getClass();
//TODO .getName() .getSimpleName() 获取类对象 -- 类的名称
System.out.println(aClass.getName()); //类的完整名称 - 包.类
System.out.println(aClass.getSimpleName()); //类名 - 类
System.out.println(aClass.getPackage()); //类的包名 - 包
//TODO .getSuperclass() 获取类的父亲
Class<?> superclass = aClass.getSuperclass();
System.out.println(superclass);
//TODO .getInterfaces() 获取类的接口 -- 可以有多个接口 -- 数组
Class<?>[] interfaces = aClass.getInterfaces();
System.out.println(interfaces.length);
//TODO 获取类的属性
Field f = aClass.getField("xxxx"); //public 修饰的指定属性
Field f1 = aClass.getDeclaredField("xxxx"); //所有权限的指定属性
Field[] fields = aClass.getFields(); //获取所有public属性 -- 数组
Field[] declaredFields = aClass.getDeclaredFields(); //获取所有权限的所有属性
//TODO 获取类的方法
Method method = aClass.getMethod("xxxx"); //public + 指定方法
Method method1 = aClass.getDeclaredMethod("xxxx"); //所有权限 + 指定方法
Method[] methods = aClass.getMethods(); //public + 所有方法
Method[] declaredMethods = aClass.getDeclaredMethods(); //所有权限 + 所有方法
//TODO .getConstructor() 构造方法
Constructor<? extends User> constructor = aClass.getConstructor();
Constructor<?>[] constructors = aClass.getConstructors();
Constructor<? extends User> declaredConstructor = aClass.getDeclaredConstructor();
Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors();
//TODO 获取权限(修饰符) -- 多个修饰符会融合成一个int值
int modifiers = aClass.getModifiers();
//TODO Modifier类提供方法通过 int 值判断权限
boolean aPrivate = Modifier.isPrivate(modifiers);
}
}
class User{
public void test1(){
}
}
class Child extends User{
public void test2(){
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)