特例:获取getter setter方法
public static void printGettersSetters(Class aClass){
Method[] methods = aClass.getMethods();
for(Method method : methods){
if(isGetter(method))
System.out.println("getter: " + method);
if(isSetter(method))
System.out.println("setter: " + method);
}
}
public static boolean isGetter(Method method){
if(!method.getName().startsWith("get"))
return false;
if(method.getParameterTypes().length != 0)
return false;
if(void.class.equals(method.getReturnType())
return false;
return true;
}
public static boolean isSetter(Method method){
if(!method.getName().startsWith("set"))
return false;
if(method.getParameterTypes().length != 1)
return false;
return true;
}
访问私有变量
获取所有变量,包含私有:
主要方法在于getDeclearedField()
使用setAccessible方法设置可见性。
访问私有方法
创建数组
//第一个参数类型,第二是大小
int[] intArray = (int[]) Array.newInstance(int.class, 3);
读写数组
Array.get(obj, index)获取数据
使用Array.set()设置值
获取元素类型
|
获取类注解
获取所有注解:
getAnnotations()获取注解,挨个遍历获取到的注解,判断其类型。
获取指定类型的注解:
获取方法注解
getDeclearedAnnotations()获取定义的注解。
也可以获取指定的类型的注解:
获取方法参数上的注解
getParameterAnnotations()获取参数注解:
变量注解
getDeclearedAnnotations()
获取指定类型的注解: