内省:javabean是java类中一个特殊的类,两个模块进行传递信息时都是将信息封装在javabean中,而jdk提供了对javabean进行操作的一些API,这套API就称之为内省。
操作javabean如下(一般用BeanUtils)
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class Bean {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Person p=new Person();
String propertyName="name";
PropertyDescriptor property=new PropertyDescriptor(propertyName,p.getClass());
Method method=property.getWriteMethod();
method.invoke(p,"dsa");
Method meth=property.getReadMethod();
Object retVal=meth.invoke(p);
System.out.println(retVal);
// BeanInfo beaninfo=Introspector.getBeanInfo(p.getClass());
// PropertyDescriptor[] propertys=beaninfo.getPropertyDescriptors();
// for(PropertyDescriptor property : propertys){
// if(property.getName().equals(propertyName)){
// Method method=property.getWriteMethod();
// method.invoke(p,"afa");
// Method meth=property.getReadMethod();
// Object retVal=meth.invoke(p);
// System.out.println(retVal);
// }
// }
}
}
class Person{
private String name="ere";
private int age;
public Person(){
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
类加载器:java虚拟机中可以安装多个类加载器,系统默认三个主要加载器分别为BootStrap、ExtClassLoader、AppClassLoader,BootStrap不是java类不需要被其他java类加载器进行加载而是嵌套在java虚拟机内核中,ExtClassLoader加载ext目录下的类而AppClassLoader是加载Classpath目录下的类
类加载器的委托机制:
当java虚拟机要加载一个类时,首先当前线程的类加载器去加载线程的第一个类,如果类A中引用了类B,java虚拟机将加载类A的类加载器去加载类B。还可以调用ClassLoader.loaderClass()方法去指定某个类加载器去加载某个类。
每个类加载加载类时又委托给其上级类加载器,当所有祖宗类加载器没有加载到类,回到发起者类加载器,还加载不了,则抛出ClassNotFoundException,不是再去找发起者类加载器的儿子。
动态代理:
程序中的代理:
要为已存在的多个具有相同接口的目标类的各个方法增加一些系统功能,例如异常处理、日志、计算方法的运行时间、事物管理等等。
编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同的方法,并在调用方法时加上系统功能的代码。
如果采用工厂模式和配置文件的方式进行管理,则不需要修改客户端程序,在配置文件中配置是使用目标类还是代理类,这样很容易以后切换,譬如想要日志功能就配置代理类,否则配置目标类,这样增强系统功能都很容易,以后运行一断时间后,又想去掉系统功能也很容易。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyTest {
public static void main(String[] args) {
Collection collection=(Collection)Proxy.newProxyInstance(Collection.class.getClassLoader()
,new Class[]{Collection.class}
,new InvocationHandler() {
Collection target=new ArrayList();
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object obj=method.invoke(target,args);
return obj;
}
});
collection.add(1);
collection.add(2);
System.out.println(collection.size());
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------