public class Main{
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Class<User> c = User.class;
User user = c.newInstance(); // 通过反射实例化对象
Field[] fields = c.getFields(); // 获取所有字段
Method[] methods = c.getMethods(); // 获取所有方法,包括从父类继承的
Method[] declaredMethods = c.getDeclaredMethods(); // 获取所有方法,不包括从父类继承的
String simpleName = c.getSimpleName(); // 获取类简单的名字(User,不带包名)
Constructor<?>[] constructors = c.getConstructors(); // 获取所有的构造方法
for (Field f : fields) {
String name = f.getName(); // 字段名称
Annotation[] annotations = f.getAnnotations(); // 获取字段上的所有注解
Class<?> type = f.getType(); // 获取字段类型
String typeName = f.getGenericType().getTypeName(); // 获取字段类型名
}
for (Method m : methods) {
Annotation[] annotations = m.getAnnotations(); // 获取方法上的所有注解
Parameter[] parameters = m.getParameters(); // 获取方法上所有的参数
for (Parameter p : parameters) {
String name = p.getName(); // 形参名字
Class<?> type = p.getType();// 形参完整类型(一般不使用)
String typeName = p.getParameterizedType().getTypeName(); // 形参类型名字
}
}
}
}
Java 反射相关方法学习总结
最新推荐文章于 2024-01-28 12:42:35 发布