Java反射-操作Field、Method、Constructo
2018-08-30 本文已影响0人
沐兮_d64c
1,Field、Method、Constructor中的反射数据
1)Field类
image.png
2)Method类
image.png
3)Constructor类
image.png
4)TheAccessibleObject
class is the base class for Field, Method and
Constructor objects.
image.png
2,打印所有成员变量、方法、构造器
public static void main(String[] args) {
Field[] fields = String.class.getDeclaredFields();
for(Field field : fields){
field.setAccessible(true);
System.out.println(Modifier.toString(field.getModifiers()) + " " + field.getType().getSimpleName() + " " + field.getName() + ";");
}
System.out.println("----------------------------");
Method[] methods = String.class.getDeclaredMethods();
for(Method method : methods){
method.setAccessible(true);
String temp = Modifier.toString(method.getModifiers()) + " " + method.getReturnType() + " "
+ method.getName() + "(";
for(Class clazz : method.getParameterTypes()){
temp += clazz.getSimpleName() + ",";
}
temp = temp.substring(0, (temp.lastIndexOf(",") == -1)?temp.length():temp.lastIndexOf(","));
temp += ")";
System.out.println(temp);
}
System.out.println("----------------------------");
Constructor[] constructors = String.class.getDeclaredConstructors();
for(Constructor constructor : constructors){
constructor.setAccessible(true);
String temp = Modifier.toString(constructor.getModifiers()) + " " + constructor.getName() + "(";
for(Class clazz : constructor.getParameterTypes()){
temp += clazz.getSimpleName() + ", ";
}
temp = temp.substring(0, (temp.lastIndexOf(",") == -1)?temp.length():temp.lastIndexOf(","));
temp += ")";
System.out.println(temp);
}
}
3,Field、Method、Constructor上
1)
是否有指定注解(自定义注解的处理)
2)modifier判断
public static void main(String[] args) throws Exception {
Method method = Class.class.getDeclaredMethod("newInstance", null);
if(method.isAnnotationPresent(CallerSensitive.class)){
System.out.println(method.getDeclaringClass());
System.out.println(Modifier.isStatic(method.getModifiers()));
System.out.println(Modifier.isPublic(method.getModifiers()));
System.out.println(Modifier.isPrivate(method.getModifiers()));
}
Field field = Class.class.getDeclaredField("name");
if(!field.isAnnotationPresent(CallerSensitive.class)){
System.out.println(field.getName());
System.out.println(Modifier.isStatic(field.getModifiers()));
System.out.println(Modifier.isPublic(field.getModifiers()));
System.out.println(Modifier.isPrivate(field.getModifiers()));
}
Constructor constructor = Class.class.getDeclaredConstructor(ClassLoader.class);
if(!constructor.isAnnotationPresent(CallerSensitive.class)){
System.out.println(constructor.getDeclaringClass());
System.out.println(Modifier.isStatic(constructor.getModifiers()));
System.out.println(Modifier.isPublic(constructor.getModifiers()));
System.out.println(Modifier.isPrivate(constructor.getModifiers()));
}
}