本帖最后由 苏周周 于 2014-6-18 09:43 编辑
今天面试问到了代理:我下午回来学习了代理:如下代码;
package cn.itheima;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class Test {
public static void main(String[] args) throws Exception, Exception {
Class clazzProxy=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
System.out.println(clazzProxy.getName());
Constructor[] constructors = clazzProxy.getConstructors();
for (Constructor constructor:constructors) {
String name = constructor.getName();
StringBuilder sb = new StringBuilder(name);
sb.append('(');
Class[] parameterTypes = constructor.getParameterTypes();
for(Class parameterType:parameterTypes){
String name2 = parameterType.getName();
sb.append(name2+',');
if(parameterTypes.length!=0&¶meterTypes!=null)
sb.deleteCharAt(sb.length()-1);
}
sb.append(')');
System.out.println(sb.toString());
}
Method[] mehtods = clazzProxy.getMethods();
for (Method mehtod:mehtods) {
String name1 = mehtod.getName();
StringBuilder sb1 = new StringBuilder(name1);
sb1.append('(');
Class[] parameterTypes1 = mehtod.getParameterTypes();
for(Class parameterType:parameterTypes1){
String name2 = parameterType.getName();
sb1.append(name2+',');
if(parameterTypes1.length!=0&¶meterTypes1!=null)
sb1.deleteCharAt(sb1.length()-1);
}
sb1.append(')');
System.out.println(sb1.toString());
System.out.println("==============================");
Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
Collection newInstance = (Collection) constructor.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
});
System.out.println(newInstance);
}
}
} |
|