1什么是反射
2如何获得一个类的 字节码 文件
使用类的全路径
Class<?> clazz = Class.forName("com.xuzhu.reflect.Person");
类型.class
Class clazz = Person.class;
对象.getClass()
Person person = new Person();
Class clazz = person.getClass();
3获得类的所有属性
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
String fieldName = field.getName();
System.out.println("fieldName:" + fieldName);
}
4获取类的所有方法
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
String methodName = method.getName();
System.out.println("methodName:" + methodName);
}
5通过反射调用方法
//调用setAge()\getAge()方法
Method setAge = clazz.getDeclaredMethod("setAge", Integer.class);
Object instance = clazz.newInstance();
setAge.invoke(instance, new Integer(1));
Method getAge = clazz.getDeclaredMethod("getAge");
System.out.println(getAge.invoke(instance));
以上是Java反射的一些基础操作,后续将介绍如果通过反射实现
Spring中Autowired注解
微信公众号搜索【虚竹讲程序经】,关注不迷路,多敲代码,不掉头发,我们下期再见!