/** * 生成代理对象 * @param targetClass 被代理对象的类型(类或接口) * @param target 被代理对象实例 * @return 代理对象 */ @SuppressWarnings("unchecked") public <T> T newProxyInstance(final Class<T> targetClass, final Object target) { return (T) Enhancer.create(targetClass, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(targetClass, method, args); Object ret = null; try { ret = method.invoke(target, args); } catch (Exception e) { exception(targetClass, method, args, e); } after(targetClass, method, args); return ret; } }); }
@Override @SuppressWarnings("unchecked") public <T> T newProxyInstance(final Class<T> targetClass, final Object target) { return (T) Enhancer.create(targetClass, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /** * 如果没有@Transaction,则直接调用原方法 */ if (!method.isAnnotationPresent(Transaction.class)) { return method.invoke(target, args); } before(targetClass, method, args); Object ret = null; try { ret = method.invoke(target, args); } catch (Exception e) { exception(targetClass, method, args, e); } after(targetClass, method, args); return ret; } }); }
/** * Build CGLIB <i>implementee</i> bean. * * @param implementation * @param implementorBeanFactory * @return */ protected Object doBuild( Implementation<?> implementation, ImplementorBeanFactory implementorBeanFactory) { InvocationHandler invocationHandler = new CglibImplementeeInvocationHandler( implementation, implementorBeanFactory, implementeeMethodInvocationFactory); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(new Class[] { CglibImplementee.class }); enhancer.setSuperclass(implementation.getImplementee()); enhancer.setCallback(invocationHandler); return enhancer.create(); }
private ServletWebRequest getSuperPoweredRequest(ServletWebRequest request, HttpServletRequest superPoweredMockRequest) { if (isSuperPowered(request)) { return request; } Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SingularServletWebRequest.class); enhancer.setInterfaces(new Class[]{SuperPowered.class}); enhancer.setCallback(new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws InvocationTargetException, IllegalAccessException { if ("getContainerRequest".equals(method.getName())) { return superPoweredMockRequest; } return method.invoke(request, objects); } }); return (ServletWebRequest) enhancer.create(); }
@Nullable public static DomInvocationHandler getDomInvocationHandler(DomElement proxy) { if (proxy instanceof DomFileElement) { return null; } if (proxy instanceof DomInvocationHandler) { return (DomInvocationHandler)proxy; } final InvocationHandler handler = AdvancedProxy.getInvocationHandler(proxy); if (handler instanceof StableInvocationHandler) { //noinspection unchecked final DomElement element = ((StableInvocationHandler<DomElement>)handler).getWrappedElement(); return element == null ? null : getDomInvocationHandler(element); } if (handler instanceof DomInvocationHandler) { return (DomInvocationHandler)handler; } return null; }
@Nullable public static DomInvocationHandler getDomInvocationHandler(DomElement proxy) { if (proxy instanceof DomFileElement) { return null; } if (proxy instanceof DomInvocationHandler) { return (DomInvocationHandler)proxy; } final InvocationHandler handler = AdvancedProxy.getInvocationHandler(proxy); if (handler instanceof StableInvocationHandler) { final DomElement element = ((StableInvocationHandler<DomElement>)handler).getWrappedElement(); return element == null ? null : getDomInvocationHandler(element); } if (handler instanceof DomInvocationHandler) { return (DomInvocationHandler)handler; } return null; }
public static Class<?> getProxyClass(Class<?> clazz) { Enhancer e = new Enhancer(); if (clazz.isInterface()) { e.setSuperclass(clazz); } else { e.setSuperclass(clazz); e.setInterfaces(clazz.getInterfaces()); } e.setCallbackTypes(new Class[]{ InvocationHandler.class, NoOp.class, }); e.setCallbackFilter(BAD_OBJECT_METHOD_FILTER); e.setUseFactory(true); e.setNamingPolicy(new LithiumTestProxyNamingPolicy()); return e.createClass(); }
@Nullable public static DomInvocationHandler getDomInvocationHandler(DomElement proxy) { if(proxy instanceof DomFileElement) { return null; } if(proxy instanceof DomInvocationHandler) { return (DomInvocationHandler) proxy; } final InvocationHandler handler = AdvancedProxy.getInvocationHandler(proxy); if(handler instanceof StableInvocationHandler) { //noinspection unchecked final DomElement element = ((StableInvocationHandler<DomElement>) handler).getWrappedElement(); return element == null ? null : getDomInvocationHandler(element); } if(handler instanceof DomInvocationHandler) { return (DomInvocationHandler) handler; } return null; }
@SuppressWarnings("unchecked") public static <T> T newProxyInstance(Class<T> clazz, final Object target) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(clazz); enhancer.setCallback(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("invoked by proxy"); return method.invoke(target, args); } }); return (T) enhancer.create(); }
public void testExtendClass() throws Throwable { final List<String> invocations = new ArrayList<String>(); Implementation implementation = AdvancedProxy.createProxy(Implementation.class, new Class[]{Interface3.class}, new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { invocations.add(method.getName()); if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } return Implementation.class.getMethod("getField").invoke(proxy); } }, "239"); implementation.hashCode(); implementation.method(); assertEquals("239", implementation.getFoo()); implementation.setField("42"); assertEquals("42", implementation.getBar()); assertEquals("42", implementation.toString()); assertEquals(Arrays.asList("hashCode", "getFoo", "getFoo", "getBar"), invocations); assertEquals("42", Interface1.class.getMethod("getFoo").invoke(implementation)); assertEquals("42", Interface3.class.getMethod("bar").invoke(implementation)); assertEquals("42", Interface1.class.getMethod("foo").invoke(implementation)); assertEquals("42", Interface2.class.getMethod("foo").invoke(implementation)); assertEquals("42", Interface2.class.getMethod("foo").invoke(implementation)); assertEquals("42", Implementation.class.getMethod("foo").invoke(implementation)); }
public static Class getProxyFactory(Class persistentClass, Class[] interfaces) throws HibernateException { Enhancer e = new Enhancer(); e.setSuperclass( interfaces.length == 1 ? persistentClass : null ); e.setInterfaces(interfaces); e.setCallbackTypes(new Class[]{ InvocationHandler.class, NoOp.class, }); e.setCallbackFilter(FINALIZE_FILTER); e.setUseFactory(false); e.setInterceptDuringConstruction( false ); return e.createClass(); }
private URLClassLoader createProxy(final ClassLoader cl) throws MalformedURLException { Enhancer e = new Enhancer(); e.setSuperclass(URLClassLoader.class); e.setCallback(new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getResources") && "META-INF/persistence.xml".equals((String) args[0])) { final String persistenceContent = generateXml(); final File file = getTempFile(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bufferedWriter.write(persistenceContent); bufferedWriter.close(); final URL url = file.toURI().toURL(); return java.util.Collections.enumeration(new HashSet<URL>(Arrays.asList(url))); } else { return method.invoke(cl, args); } } }); URL[] arrayDeURL = new URL[] { new URL("http://google.com.br") }; Class<?>[] array = new Class<?>[] { arrayDeURL.getClass() }; URLClassLoader f = (URLClassLoader) e.create(array, new Object[] { arrayDeURL }); return f; }
public Object createInterceptorFor(Object instanceToIntercept) { if (getInterceptorClassToBeUsed() != null) { try { // Class[] parameterTypes = {Object.class}; // Object[] parameters = {instanceToIntercept}; // Constructor constructor = getInterceptorClassToBeUsed().getConstructor(parameterTypes); // InvocationHandler handler = (InvocationHandler) constructor.newInstance(parameters); // use helper class to instantiate InvocationHandler handler = (InvocationHandler) ClassHelper.newInstance( getInterceptorClassToBeUsed(), Object.class, instanceToIntercept); Class[] interfaces = computeInterfaceArrayFor(instanceToIntercept.getClass()); Object result = Proxy.newProxyInstance( ClassHelper.getClassLoader(), interfaces, handler); return result; } catch (Throwable t) { LoggerFactory.getDefaultLogger().error("can't use Interceptor " + getInterceptorClassToBeUsed().getName() + "for " + instanceToIntercept.getClass().getName(), t); return instanceToIntercept; } } else { return instanceToIntercept; } }
public static InvocationHandler getInvocationHandler(Object proxy) { return (InvocationHandler)((Factory)proxy).getCallback(0); }
@SuppressWarnings("unchecked") private static void copyDelegateFields(Object target, InvocationHandler source) { Object obj = ((RemoteProxy)source).obj; if (obj == null) { return; } if (!(obj.getClass().getClassLoader() instanceof FunctionalTestClassLoader)) { throw new ClassLoaderException("Failed wrapping field on remote object - wrong classloader type"); } FunctionalTestClassLoader classLoader = (FunctionalTestClassLoader)obj.getClass().getClassLoader(); // get the source fields Field[] fields = getAllFields(obj.getClass()); // get the target proxy parent fields Field[] targetFields = getAllFields(target.getClass().getSuperclass()); for(Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { /** * The @TestVisible annotation tells the framework to automatically bring the value * from the child classloader into the proxy for easy access during a test. * * @TestVisible * @Autowired * private final MyInterface myDependencyInjectedValue = null; * * ... * { * ... * myTestClass.myDependencyInjectedValue.getValue(); * ... * } * */ Class<? extends Annotation> testVisible; testVisible = (Class<? extends Annotation>)getClassFromClassLoader(TestVisible.class, classLoader); if (field.isAnnotationPresent(testVisible)) { // copy the values over for final fields Field targetField = null; try { for(Field f : targetFields) { if (f.getName().equals(field.getName())) { targetField = f; } } } catch (Exception e) { // benign } if (targetField != null) { copyProxiedValue(field, obj, targetField, target, classLoader); } } } } }
/** * Specifies the scoped provider. Every method call on the object created by this * builder will be delegated to the object returned by the given provider. * <p> * This method overrides the callback set by {@link #withCallback(Callback)}. * * @param provider The scoped provider. * @return Builder object for further configuration. * @see #withCallback(Callback) */ public InstanceBuilder<T> dispatchTo(Provider<T> provider) { Preconditions.checkNotNull(provider, "provider"); final InvocationHandler callback = (proxy, method, args) -> method .invoke(provider.get(), args); this.dispatcher = callback; return this; }
/** * Instantiates a new {@link AbstractClassProxyFactory}. * * @param handler handles */ AbstractClassProxyFactory(final InvocationHandler handler) { this.handler = checkNotNull(handler, "handler cannot be null"); }