首页 > 代码库 > Java 动态创建类

Java 动态创建类

/*
* 动态创建代理类
*/
public static <T> T getProxy(Class<?> interfaceType,final Object target) throws Exception{

      if(!interfaceType.isInterface()){
     throw new Exception("接口类型不正确!");
  }

  @SuppressWarnings("unchecked")
  T targerInstance=(T)Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[]{interfaceType}, new InvocationHandler() {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    System.out.println("开始");
    Object value=http://www.mamicode.com/method.invoke(target, args);
    System.out.println("结束");
    return value;
    }
  });

return targerInstance;
}

 

调用实例:

IStudent stu=getProxy(Class.forName("proxy.yl.IStudent"),Class.forName("proxy.yl.Student").newInstance());
stu.setName("xxxxx");
System.out.println(stu.getName());

Java 动态创建类