day39
反射
继day38
反射访问内容
反射操作注意设置权限
两个类Person及其子类
public class Person {
private String name;
private char sex;
private int age;
//有参、无参构造、get、set、toString方法【略】
protected static final synchronized void method(){
System.out.println("静态方法");
}
}
@MyAnnotaction(str = "aaa")
public class Student extends Person{
private String classId;
private String id;
@MyAnnotaction(str = "bbb")
public HashMap<String, Integer> map;
public static final String str = "风华雪月";
//有参、无参构造、get、set方法【略】
@Override
public String toString() {
return "Student [classId=" + classId + ", id=" + id + ", toString()=" + super.toString() + "]";//加上父类的toString
}
public void method01(){
System.out.println("无参数无返回值的方法 -- method01");
}
public void method02(String str, int i){
System.out.println("带参数的方法 -- method02:" + str + " -- " + i);
}
public String method03(){
return "无参数带返回值的方法 -- method03";
}
private String method04(String str, int i){
return "带参数带返回值的方法 -- method04:" + str + " -- " + i;
}
@MyAnnotaction(str = "ccc")
public HashMap<Character, Boolean> method05(@MyAnnotaction(str = "ddd") ArrayList<Object> list,HashMap<Number, Double> map){
return null;
}
}
操作方法
普通方法
获取方法对象、方法参数值
public class Test01 {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException {
// Properties p = new Properties();
// p.load(Test01.class.getClassLoader().getResourceAsStream("classPath.properties"));
// String path = p.getProperty("path");
// Class<?> clazz = Class.forName(path);
//获取本类及其父类公有的方法对象
// Method[] methods = clazz.getMethods();
// for (Method method : methods) {
// System.out.println(method);
// }
//获取本类所有的方法对象
// Method[] methods = clazz.getDeclaredMethods();
// for (Method method : methods) {
// System.out.println(method);
// }
//获取本类及其父类所有的方法对象
// for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
// Method[] methods = c.getDeclaredMethods();
// for (Method method : methods) {
// System.out.println(method);
// }
// }
//获取本类公有的指定名字的方法对象
// Method method = clazz.getMethod("setClassId", String.class);
// System.out.println(method);
//获取本类所有的指定名字的方法对象
// Method method = clazz.getDeclaredMethod("method");
// System.out.println(method);
//利用反射工具类获取子类及其父类指定名字的方法对象
Method method = ReflexUtil.getMethod(clazz, "method");
System.out.println(method);
//获取方法参数值
int modifiers = method.getModifiers();
System.out.println("是否使用public修饰:" + Modifier.isPublic(modifiers));
System.out.println("是否使用private修饰:" + Modifier.isPrivate(modifiers));
System.out.println("是否使用protected修饰:" + Modifier.isProtected(modifiers));
System.out.println("是否使用static修饰:" + Modifier.isStatic(modifiers));
System.out.println("是否使用final修饰:" + Modifier.isFinal(modifiers));
System.out.println("是否使用abstract修饰:" + Modifier.isAbstract(modifiers));
System.out.println("是否使用synchronized修饰:" + Modifier.isSynchronized(modifiers));
}
}
调用静态、成员方法
public class Test02 {
public