发现这篇挺难写的,因为现在的状况是我没上网条件,只能偶尔去下网吧,所以视频上说的那个BeanUtil工具包一直没用过,只知道那玩意挺方便的,做了下笔记:BeanUtil和PropertyUtils都有两个相同的方法,getProperty和setProperty,两者区别,前者会帮你自动准换,后者以本身属性操作,用的时候查文档就可以了。
所以在试验的时候我都是用jdk里面的BeanInfo来测试所学的东西,当时在看视频的时候心里想着,只要记住BeanInfo这个类就可以了,其他顺藤摸瓜即可,就像只要记住反射要用到Class这个类一样,于是我就写了几行代码测试:
package it.cast.heima;
//我把引入的类去掉了,为了在博客上省几行空间来显示其他内容
public class StudentBeanTest {
public static void main(String[] args) throws Exception {
Student s = new Student("xx",12,new Date());
Class clazz = Class.forName("it.cast.heima.Student");
BeanInfo info = Introspector.getBeanInfo(clazz);
BeanDescriptor descriptor = info.getBeanDescriptor();
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for(PropertyDescriptor pd : pds) {
if(pd.getPropertyType() == String.class) {
System.out.println(pd.getReadMethod().invoke(s, null));
}
}
//第二种方法
PropertyDescriptor pd = new PropertyDescriptor("birthday", clazz);
System.out.println(pd.getReadMethod().invoke(s, null));
}
}
至于要反射的Student类,有3属性,name,age,birthday,还分别为他们弄了get和set方法。第一种方法想当然的弄出来了,然后发现视频上说的那种也就是第二种想不出来,翻来翻去文档也似乎没有只返回一个PropertyDescriptor的方法,因为一般这类情况都只能get出来,没想到还能new出来,所以又翻看了一遍视频,才换然大悟,原来还能这么耍!!
对于代理,其实没什么好写的,只要记得一个类名,它叫Proxy就可以顺藤摸瓜摸出来,而且不会像上面那种摸着摸着摸不出= =因为视频半个月钱就看完了,想着先自己凭记忆弄下,然后再看看视频。jdk提供的只能代理那些实现了接口的类,没有实现接口的不能,所以当时自己测试的时候发现怎么只能传个Interfaced类型的的class数组进去啊,很郁闷,我还以为代理是能代理任何东西的,不过其实也没必要代理没实现接口的吧?直接反射也可以吧我觉得。
public class Person implements Run {
@Override
public void run() {
System.out.println("I am running!!");
}
public static void main(String[] args) {
Person p = new Person();
InvocationHandler h = new MyInvocationHandler(p);
Run r1 = (Run)Proxy.newProxyInstance(p.getClass().getClassLoader(),new Class[] {Run.class},h);
r1.run();
}
}
class MyInvocationHandler implements InvocationHandler {
Person p;
public MyInvocationHandler(Object p) {
this.p = (Person)p;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//beforMethod
method.invoke(p, null);
//afterMethod
return null;
}
}
这个玩意挺难整的,而且现在还感觉不出实际意义,估计只有用上视频上说的那个GClib才有点乐趣。而视频上那个例子没我的例子好。