1、利用反射获取Class对象
Class<?> c1 = Class.forName("reflace.FSTest");
Class<?> c2 = new FSTest().getClass();
Class<?> c3 = FSTest.class;
2、利用反射获取父类和接口的Class对象
利用反射获取类的父类的Class对象
Class<?> parent = c1.getSuperclass();
利用反射获取类的接口的Class对象
Class<?>[] interfaceClass = c1.getInterfaces();
Java是单继承多实现的,所以,获取父类回来的是一个Class,而获取接口的就是一个数组
3、获取本类的所有的属性
Field[] fArray = c1.getDeclaredFields();
for (int index = 0; index < fArray.length; index++) {
Field f1 = fArray[index];
//获取属性的类型,是什么类型的数据。int,string
String type = f1.getType().getName();
//获取属性名
String name = f1.getName();
//修饰符,也就是说这个属性是public还是private等等。。。
String modify = Modifier.toString(f1.getModifiers());
System.out.println("modify-->" + modify + "--type-->" + type+ "--name-->" + name);
}
4、getFields()与getDeclaredFields()区别:
getFields()只能访问类中声明为公有的字段,私有的字段它无法访问,能访问从其它类继承来的公有方法.
getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法
类似的还有: getConstructors()与getDeclaredConstructors()、getMethods()与getDeclaredMethods()
5、利用反射获取获取类中的方法
//获取类中的方法
Method method = c1.getMethod("reflect1");
//执行该方法
method.invoke(c1.newInstance());
以上获取和执行的时候需要捕获异常。NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException
6、属性值的获取和设置
Object obj = c1.newInstance();
Field field = c1.getDeclaredField("name");
System.out.println(field.get(obj));
field.setAccessible(true);
field.set(obj, "Java");
System.out.println(field.get(obj));
7、动态代理
利用InvocationHandler动态代理
测试类:
以上就是一个完整的动态代理的示例,同时也可以是这样的,网上比较多的示例代码是下面这种写法,这种看起来比较直观,比较适合于新手吧!
8、