Java Code Examples for java.lang.reflect.InvocationHandler

The following are top voted examples for showing how to use java.lang.reflect.InvocationHandler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Reer   File: ProtocolToModelAdapter.java   View source code 6 votes vote down vote up
public Object invoke(Object target, Method method, Object[] params) throws Throwable {
    if (EQUALS_METHOD.equals(method)) {
        Object param = params[0];
        if (param == null || !Proxy.isProxyClass(param.getClass())) {
            return false;
        }
        InvocationHandler other = Proxy.getInvocationHandler(param);
        return equals(other);
    } else if (HASHCODE_METHOD.equals(method)) {
        return hashCode();
    }

    MethodInvocation invocation = new MethodInvocation(method.getName(), method.getReturnType(), method.getGenericReturnType(), method.getParameterTypes(), target, targetType, sourceObject, params);
    invoker.invoke(invocation);
    if (!invocation.found()) {
        String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName() + "()";
        throw Exceptions.unsupportedMethod(methodName);
    }
    return invocation.getResult();
}
 
Example 2
Project: jdk8u-jdk   File: FullscreenEnterEventTest.java   View source code 6 votes vote down vote up
private static void enableFullScreen(Window window) {
    try {
        Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
        Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
        setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
        Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
        Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                switch (method.getName()) {
                    case "windowEnteringFullScreen":
                        windowEnteringFullScreen = true;
                        break;
                    case "windowEnteredFullScreen":
                        windowEnteredFullScreen = true;
                        break;
                }
                return null;
            }
        });
        Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener);
        addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
    } catch (Exception e) {
        throw new RuntimeException("FullScreen utilities not available", e);
    }
}
 
Example 3
Project: Simplify-Core   File: AopClassLoader.java   View source code 6 votes vote down vote up
public Class<?> defineClass(Class clazz, InvocationHandler invocationHandler) throws ClassNotFoundException {
    String clazzName = replaceClassName(clazz) + ".class";
    try {
        ClassWriter cw = new ClassWriter(0);
        //读取 被代理类
        InputStream is = clazz.getClassLoader().getResourceAsStream(clazzName);
        ClassReader reader = new ClassReader(is);
        reader.accept(new AopClassAdapter(ASM5, cw, invocationHandler), ClassReader.SKIP_DEBUG);

        byte[] code = cw.toByteArray();
        FileOutputStream fos = new FileOutputStream(AopClassLoader.class.getResource("").getPath().toString() + "/Asm_Tmp.class");
        fos.write(code);
        fos.flush();
        fos.close();
        return super.defineClass(clazz.getName() + "$simplify", code, 0, code.length);
    } catch (Throwable e) {
        System.out.println(e);
        throw new ClassNotFoundException();
    }
}
 
Example 4
Project: incubator-netbeans   File: DbDriverManagerTest.java   View source code 6 votes vote down vote up
public Connection connect(String url, Properties info) throws SQLException {
    return (Connection)Proxy.newProxyInstance(DriverImpl.class.getClassLoader(), new Class[] { ConnectionEx.class }, new InvocationHandler() {
        public Object invoke(Object proxy, Method m, Object[] args) {
            String methodName = m.getName();
            if (methodName.equals("getDriver")) {
                return DriverImpl.this;
            } else if (methodName.equals("hashCode")) {
                Integer i = new Integer(System.identityHashCode(proxy));
                return i;
            } else if (methodName.equals("equals")) {
                return Boolean.valueOf(proxy == args[0]);
            }
            return null;
        }
    });
}
 
Example 5
Project: incubator-netbeans   File: MetaInfCacheTest.java   View source code 6 votes vote down vote up
private static Object generateProxyType(final int i) {
    class DummyH implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("equals")) {
                return proxy == args[0];
            }
            if (method.getName().equals("toString")) {
                return "DummyH[" + i + "]";
            }
            return null;
        }
    }
    return Proxy.newProxyInstance(
        MetaInfCache.class.getClassLoader(),
        findTypes(i), 
        new DummyH()
    );
}
 
Example 6
Project: albedo-thrift   File: ThriftServiceClientProxyFactory.java   View source code 6 votes vote down vote up
@Override
    public void afterPropertiesSet() throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // 加载Iface接口
        objectClass = classLoader.loadClass(serverAddressProvider.getService() + "$Iface");
        // 加载Client.Factory类
        Class<TServiceClientFactory<TServiceClient>> fi =
                (Class<TServiceClientFactory<TServiceClient>>) classLoader.
                        loadClass(serverAddressProvider.getService() + "$Client$Factory");
        TServiceClientFactory<TServiceClient> clientFactory = fi.newInstance();

        ThriftClientPoolFactory clientPool = new ThriftClientPoolFactory(serverAddressProvider,
                clientFactory, callback);
        pool = new GenericObjectPool<TServiceClient>(clientPool, makePoolConfig());

//        InvocationHandler handler = makeProxyHandler();//方式1
        InvocationHandler handler = makeProxyHandler2();//方式2
        proxyClient = Proxy.newProxyInstance(classLoader, new Class[] { objectClass }, handler);
    }
 
Example 7
Project: ysoserial-plus   File: CommonsCollections3.java   View source code 6 votes vote down vote up
public Object getObject(final String command) throws Exception {
	Object templatesImpl = Gadgets.createTemplatesImpl(command);

	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(TrAXFilter.class),
			new InstantiateTransformer(
					new Class[] { Templates.class },
					new Object[] { templatesImpl } )};

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return handler;
}
 
Example 8
Project: whackpad   File: VMBridge_jdk13.java   View source code 6 votes vote down vote up
@Override
protected Object getInterfaceProxyHelper(ContextFactory cf,
                                         Class<?>[] interfaces)
{
    // XXX: How to handle interfaces array withclasses from different
    // class loaders? Using cf.getApplicationClassLoader() ?
    ClassLoader loader = interfaces[0].getClassLoader();
    Class<?> cl = Proxy.getProxyClass(loader, interfaces);
    Constructor<?> c;
    try {
        c = cl.getConstructor(new Class[] { InvocationHandler.class });
    } catch (NoSuchMethodException ex) {
        // Should not happen
        throw Kit.initCause(new IllegalStateException(), ex);
    }
    return c;
}
 
Example 9
Project: ServiceHook   File: ServiceHook.java   View source code 6 votes vote down vote up
public HookHandler(IBinder base, Class<?> stubClass,
                   InvocationHandler InvocationHandler) {
    mInvocationHandler = InvocationHandler;

    try {
        Method asInterface = stubClass.getDeclaredMethod("asInterface", IBinder.class);
        this.mBase = asInterface.invoke(null, base);

        Class clazz = mBase.getClass();
        Field mRemote = clazz.getDeclaredField("mRemote");
        mRemote.setAccessible(true);
        //新建一个 BinderProxy 的代理对象
        Object binderProxy = Proxy.newProxyInstance(mBase.getClass().getClassLoader(),
                new Class[] {IBinder.class}, new TransactionWatcherHook((IBinder) mRemote.get(mBase), (IInterface) mBase));
        mRemote.set(mBase, binderProxy);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Project: spring-cloud-sockets   File: ReactiveSocketClient.java   View source code 6 votes vote down vote up
public <T> T create(final Class<T> service) {
	if(!service.isInterface()){
		throw new IllegalArgumentException("service must be an interface");
	}

	return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service }, new InvocationHandler() {
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			AbstractRemoteHandler handler = handlerFor(method);
			if(handler == null){
				return null;
			}
			return handler.invoke(args[0]);
		}
	});
}
 
Example 11
Project: XXXX   File: FeignBuilderTest.java   View source code 6 votes vote down vote up
@Test
public void testProvideInvocationHandlerFactory() throws Exception {
  server.enqueue(new MockResponse().setBody("response data"));

  String url = "http://localhost:" + server.getPort();

  final AtomicInteger callCount = new AtomicInteger();
  InvocationHandlerFactory factory = new InvocationHandlerFactory() {
    private final InvocationHandlerFactory delegate = new Default();

    @Override
    public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
      callCount.incrementAndGet();
      return delegate.create(target, dispatch);
    }
  };

  TestInterface api =
      Feign.builder().invocationHandlerFactory(factory).target(TestInterface.class, url);
  Response response = api.codecPost("request data");
  assertEquals("response data", Util.toString(response.body().asReader()));
  assertEquals(1, callCount.get());

  assertThat(server.takeRequest())
      .hasBody("request data");
}
 
Example 12
Project: TPlayer   File: ProxyServiceFactory.java   View source code 6 votes vote down vote up
@Override
public IBinder getService(final Context context, ClassLoader classLoader, IBinder binder) {
	return new StubBinder(classLoader, binder) {
		@Override
		public InvocationHandler createHandler(Class<?> interfaceClass, final IInterface base) {
			return new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					try {
						return method.invoke(base, args);
					} catch (InvocationTargetException e) {
						if (e.getCause() != null) {
							throw e.getCause();
						}
						throw e;
					}
				}
			};
		}
	};
}
 
Example 13
Project: openjdk-jdk10   File: ProxyArrays.java   View source code 6 votes vote down vote up
/**
 * Generate proxy arrays.
 */
Proxy[][] genArrays(int size, int narrays) throws Exception {
    Class proxyClass =
        Proxy.getProxyClass(DummyInterface.class.getClassLoader(),
                new Class[] { DummyInterface.class });
    Constructor proxyCons =
        proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    Object[] consArgs = new Object[] { new DummyHandler() };
    Proxy[][] arrays = new Proxy[narrays][size];
    for (int i = 0; i < narrays; i++) {
        for (int j = 0; j < size; j++) {
            arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs);
        }
    }
    return arrays;
}
 
Example 14
Project: container   File: ProxyServiceFactory.java   View source code 6 votes vote down vote up
@Override
public IBinder getService(final Context context, ClassLoader classLoader, IBinder binder) {
	return new StubBinder(classLoader, binder) {
		@Override
		public InvocationHandler createHandler(Class<?> interfaceClass, final IInterface base) {
			return new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					try {
						return method.invoke(base, args);
					} catch (InvocationTargetException e) {
						if (e.getCause() != null) {
							throw e.getCause();
						}
						throw e;
					}
				}
			};
		}
	};
}
 
Example 15
Project: openjdk-jdk10   File: NonPublicProxyClass.java   View source code 6 votes vote down vote up
private void newInstanceFromConstructor(Class<?> proxyClass)
    throws Exception
{
    // expect newInstance to succeed if it's in the same runtime package
    boolean isSamePackage = proxyClass.getName().lastIndexOf('.') == -1;
    try {
        Constructor cons = proxyClass.getConstructor(InvocationHandler.class);
        cons.newInstance(newInvocationHandler());
        if (!isSamePackage) {
            throw new RuntimeException("ERROR: Constructor.newInstance should not succeed");
        }
    }  catch (IllegalAccessException e) {
        if (isSamePackage) {
            throw e;
        }
    }
}
 
Example 16
Project: apm-client   File: TraceProxyFactory.java   View source code 6 votes vote down vote up
private InvocationHandler createInvocationHandler(final Object instance) {
  return new InvocationHandler() {
      @Override
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(!shouldTrace(method)) {
          return method.invoke(instance, args);
        }

        SpanBuilder span = tracer.createSpan();
        try {
          return method.invoke(instance, args);
        }
        catch (InvocationTargetException e) {
          final Throwable cause = e.getCause();
          span.exception(cause);
          throw cause;
        }
        finally {
          span.resource(method.getDeclaringClass().getCanonicalName()).operation(method.getName());
          tracer.closeSpan(span);
        }
      }
    };
}
 
Example 17
Project: APacheSynapseSimplePOC   File: Spring2.java   View source code 6 votes vote down vote up
public Object getObject ( final String command ) throws Exception {
    final Object templates = Gadgets.createTemplatesImpl(command);

    AdvisedSupport as = new AdvisedSupport();
    as.setTargetSource(new SingletonTargetSource(templates));

    final Type typeTemplatesProxy = Gadgets.createProxy(
        (InvocationHandler) Reflections.getFirstCtor("org.springframework.aop.framework.JdkDynamicAopProxy").newInstance(as),
        Type.class,
        Templates.class);

    final Object typeProviderProxy = Gadgets.createMemoitizedProxy(
        Gadgets.createMap("getType", typeTemplatesProxy),
        forName("org.springframework.core.SerializableTypeWrapper$TypeProvider"));

    Object mitp = Reflections.createWithoutConstructor(forName("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider"));
    Reflections.setFieldValue(mitp, "provider", typeProviderProxy);
    Reflections.setFieldValue(mitp, "methodName", "newTransformer");
    return mitp;
}
 
Example 18
Project: OpenJSharp   File: WSServiceDelegate.java   View source code 6 votes vote down vote up
private <T> T createEndpointIFBaseProxy(@Nullable WSEndpointReference epr, QName portName, Class<T> portInterface,
                                        WebServiceFeatureList webServiceFeatures, SEIPortInfo eif) {
    //fail if service doesnt have WSDL
    if (wsdlService == null) {
        throw new WebServiceException(ClientMessages.INVALID_SERVICE_NO_WSDL(serviceName));
    }

    if (wsdlService.get(portName)==null) {
        throw new WebServiceException(
            ClientMessages.INVALID_PORT_NAME(portName,buildWsdlPortNames()));
    }

    BindingImpl binding = eif.createBinding(webServiceFeatures, portInterface);
    InvocationHandler pis = getStubHandler(binding, eif, epr);

    T proxy = createProxy(portInterface, pis);

    if (serviceInterceptor != null) {
        serviceInterceptor.postCreateProxy((WSBindingProvider)proxy, portInterface);
    }
    return proxy;
}
 
Example 19
Project: alfresco-repository   File: PolicyFactory.java   View source code 6 votes vote down vote up
/**
 * Construct a collection of Policy implementations for the specified binding
 * 
 * @param binding  the binding
 * @return  the collection of policy implementations
 */
@SuppressWarnings("unchecked")
public Collection<P> createList(B binding)
{
    Collection<BehaviourDefinition> behaviourDefs = index.find(binding);
    List<P> policyInterfaces = new ArrayList<P>(behaviourDefs.size());
    for (BehaviourDefinition behaviourDef : behaviourDefs)
    {
        Behaviour behaviour = behaviourDef.getBehaviour();
        P policyIF = behaviour.getInterface(policyClass);
        if (!(behaviour.getNotificationFrequency().equals(NotificationFrequency.EVERY_EVENT)))
        {
            // wrap behaviour in transaction proxy which deals with delaying invocation until necessary
            if (transactionHandlerFactory == null)
            {
                throw new PolicyException("Transaction-level policies not supported as transaction support for the Policy Component has not been initialised.");
            }
            InvocationHandler trxHandler = transactionHandlerFactory.createHandler(behaviour, behaviourDef.getPolicyDefinition(), policyIF);
            policyIF = (P)Proxy.newProxyInstance(policyClass.getClassLoader(), new Class[]{policyClass}, trxHandler);
        }
        policyInterfaces.add(policyIF);
    }
    
    return policyInterfaces;
}
 
Example 20
Project: jaffa-framework   File: OracleJDBCDelegate.java   View source code 6 votes vote down vote up
/** Quartz-1.6.x wraps the original Connection inside a Proxy.
 * This method will extract the original Connection, allowing access to vendor specific operations
 */
private Connection extractWrappedConnection(Connection conn) {
    if (conn instanceof Proxy) {
        try {
            if (log.isDebugEnabled())
                log.debug("Extracting a WrappedConnection from the Proxy: " + conn);
            Proxy connProxy = (Proxy) conn;
            InvocationHandler invocationHandler = Proxy.getInvocationHandler(connProxy);
            Method m = invocationHandler.getClass().getMethod("getWrappedConnection");
            if (Connection.class.isAssignableFrom(m.getReturnType())) {
                Connection wrappedConnection = (Connection) m.invoke(invocationHandler);
                if (log.isDebugEnabled())
                    log.debug("Extracted WrappedConnection: " + wrappedConnection);
                return wrappedConnection;
            } else {
                if (log.isDebugEnabled())
                    log.debug("WrappedConnection cannot be extracted since the method 'public Connection getWrappedConnection()' is missing from the InvocationHandler: " + invocationHandler);
            }
        } catch (Exception e) {
            // do nothing
            if (log.isDebugEnabled())
                log.debug("Exception in obtaining the WrappedConnection from the Proxy: " + conn, e);
        }
    }
    return conn;
}
 
Example 21
Project: ysoserial-modified   File: Spring2.java   View source code 6 votes vote down vote up
public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception {
    final Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());

    AdvisedSupport as = new AdvisedSupport();
    as.setTargetSource(new SingletonTargetSource(templates));

    final Type typeTemplatesProxy = Gadgets.createProxy(
        (InvocationHandler) Reflections.getFirstCtor("org.springframework.aop.framework.JdkDynamicAopProxy").newInstance(as),
        Type.class,
        Templates.class);

    final Object typeProviderProxy = Gadgets.createMemoitizedProxy(
        Gadgets.createMap("getType", typeTemplatesProxy),
        forName("org.springframework.core.SerializableTypeWrapper$TypeProvider"));

    Object mitp = Reflections.createWithoutConstructor(forName("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider"));
    Reflections.setFieldValue(mitp, "provider", typeProviderProxy);
    Reflections.setFieldValue(mitp, "methodName", "newTransformer");
    return mitp;
}
 
Example 22
Project: AFRouter   File: AFRouter.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
private <T> T create(final Class<T> service, final Wrapper wrapper, final Interceptor interceptor) {
    Object proxyInstance = Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object... args) throws Throwable {
                    if (method.getDeclaringClass() == Object.class) { // filter Object method
                        return method.invoke(this, args);
                    }
                    wrapper.setMethod(method);
                    wrapper.setMethodArgs(args);
                    Class returnType = method.getReturnType();
                    if (returnType == void.class) {
                        if (interceptor == null || !interceptor.intercept(wrapper)) {
                            wrapper.start();
                        }
                        return null;
                    } else if (returnType == Wrapper.class) {
                        return wrapper;
                    } else {
                        throw new RuntimeException("method return type only support 'void' or 'Wrapper'");
                    }
                }
            });
    return (T) proxyInstance;
}
 
Example 23
Project: uavstack   File: DynamicProxyInstaller.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static Object adapt(Object t) {

    if (!Proxy.isProxyClass(t.getClass())) {
        return t;
    }

    InvocationHandler ih = Proxy.getInvocationHandler(t);

    if (ih == null) {
        return t;
    }

    if (!JDKProxyInvokeHandler.class.isAssignableFrom(ih.getClass())) {
        return t;
    }

    JDKProxyInvokeHandler jpih = (JDKProxyInvokeHandler) ih;

    return jpih.getTarget();
}
 
Example 24
Project: nymph   File: AopUtils.java   View source code 6 votes vote down vote up
/**
 * 获取代理对象, jdk的代理对象只能强转成父类才能正常使用, 所以他必须实现一个接口
 * @param target	被代理的对象Class
 * @param h			代理的具体操作在此对象的invoke方法内进行
 * @return			jdk的代理对象
 */
public static Object getProxy(Class<?> target, InvocationHandler h) {
	Class<?>[] interfaces = null;
	if (target.isInterface()) {
		interfaces = new Class<?>[]{target};
	}

	if (interfaces == null) {
		interfaces = target.getInterfaces();
		if (interfaces.length == 0) {
			throw new IllegalArgumentException("target必须为接口或者接口的实现类");
		}
	}

	return Proxy.newProxyInstance(BasicUtil.getDefaultClassLoad(), interfaces, h);
}
 
Example 25
Project: ysoserial-modified   File: Jdk7u21.java   View source code 6 votes vote down vote up
public Object getObject(CmdExecuteHelper cmdHelper) throws Exception {
	final Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());

	String zeroHashCodeStr = "f5a5a608";

	HashMap map = new HashMap();
	map.put(zeroHashCodeStr, "foo");

	InvocationHandler tempHandler = (InvocationHandler) Reflections.getFirstCtor(Gadgets.ANN_INV_HANDLER_CLASS).newInstance(Override.class, map);
	Reflections.setFieldValue(tempHandler, "type", Templates.class);
	Templates proxy = Gadgets.createProxy(tempHandler, Templates.class);

	LinkedHashSet set = new LinkedHashSet(); // maintain order
	set.add(templates);
	set.add(proxy);

	Reflections.setFieldValue(templates, "_auxClasses", null);
	Reflections.setFieldValue(templates, "_class", null);

	map.put(zeroHashCodeStr, templates); // swap in real object

	return set;
}
 
Example 26
Project: xm-ms-entity   File: LepServiceFactoryBean.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object getObject() throws Exception {
    InvocationHandler invocationHandler = (proxy, method, args) -> {
        if (isToString(method)) {
            return "LepService proxy for: " + getObjectType().getCanonicalName();
        } else if (isObjectMethod(method)) {
            // other objects methods
            return method.invoke(proxy, args);
        }

        // execute LEP method
        return lepServiceHandler.onMethodInvoke(type, null, method, args);
    };

    return Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, invocationHandler);
}
 
Example 27
Project: PhotoOut   File: ProxyTools.java   View source code 5 votes vote down vote up
public static <T> T getShowMethodInfoProxy(final T realObj){
    return (T) Proxy.newProxyInstance(ProxyTools.class.getClassLoader(), realObj.getClass().getInterfaces(), new InvocationHandler() {

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            XLog.e("method name:"+ method.getName() + "--args:"+ Arrays.toString(args));
            Object o = method.invoke(realObj,args);
            return o;
        }
    });
}
 
Example 28
Project: lams   File: JRubyScriptUtils.java   View source code 5 votes vote down vote up
private boolean isProxyForSameRubyObject(Object other) {
	if (!Proxy.isProxyClass(other.getClass())) {
		return false;
	}
	InvocationHandler ih = Proxy.getInvocationHandler(other);
	return (ih instanceof RubyObjectInvocationHandler &&
			this.rubyObject.equals(((RubyObjectInvocationHandler) ih).rubyObject));
}
 
Example 29
Project: apache-tomcat-7.0.73-with-comment   File: DataSourceLinkFactory.java   View source code 5 votes vote down vote up
protected Object wrapDataSource(Object datasource, String username, String password) throws NamingException {
    try {
        Class<?> proxyClass = Proxy.getProxyClass(datasource.getClass().getClassLoader(), datasource.getClass().getInterfaces());
        Constructor<?> proxyConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
        DataSourceHandler handler = new DataSourceHandler((DataSource)datasource, username, password);
        return proxyConstructor.newInstance(handler);    
    }catch (Exception x) {
        if (x instanceof InvocationTargetException) {
            Throwable cause = x.getCause();
            if (cause instanceof ThreadDeath) {
                throw (ThreadDeath) cause;
            }
            if (cause instanceof VirtualMachineError) {
                throw (VirtualMachineError) cause;
            }
            if (cause instanceof Exception) {
                x = (Exception) cause;
            }
        }
        if (x instanceof NamingException) throw (NamingException)x;
        else {
            NamingException nx = new NamingException(x.getMessage());
            nx.initCause(x);
            throw nx;
        }
    }
}
 
Example 30
Project: hadoop   File: RetryInvocationHandler.java   View source code 5 votes vote down vote up
@VisibleForTesting
static boolean isRpcInvocation(Object proxy) {
  if (proxy instanceof ProtocolTranslator) {
    proxy = ((ProtocolTranslator) proxy).getUnderlyingProxyObject();
  }
  if (!Proxy.isProxyClass(proxy.getClass())) {
    return false;
  }
  final InvocationHandler ih = Proxy.getInvocationHandler(proxy);
  return ih instanceof RpcInvocationHandler;
}
 
Example 31
Project: org.ops4j.pax.transx   File: Wrappers.java   View source code 5 votes vote down vote up
private static Object wrap(Class<?> clazz, ConnectionHandle c, Object h, List<InvocationHandler> subHandlers) {
    if (h == null) {
        return null;
    }
    InvocationHandler ih = (proxy, method, args) -> {
        try {
            for (InvocationHandler sih : subHandlers) {
                Object o = sih.invoke(proxy, method, args);
                if (o != UNHANLED) {
                    return o;
                }
            }
            Object result = method.invoke(h, args);
            if (CLASSES_TO_WRAP.contains(method.getReturnType())) {
                result = wrap(method.getReturnType(), c, result,
                              Arrays.asList(wrapperIh(result), statementIh(c, result), getConnectionIh(c)));
            }
            return result;
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof Exception) {
                c.connectionError((Exception) t);
            }
            throw e;
        }
    };
    return Proxy.newProxyInstance(h.getClass().getClassLoader(), new Class[] { clazz }, ih);
}
 
Example 32
Project: uroborosql   File: Helper.java   View source code 5 votes vote down vote up
public static ResultSet newResultSet(final Object... defs) throws NoSuchMethodException, SecurityException {
	if (defs.length % 2 != 0) {
		throw new IllegalArgumentException();
	}

	Method wasNull = ResultSet.class.getMethod("wasNull");

	Map<Method, Object> values = new HashMap<>();
	for (int i = 0; i < defs.length; i += 2) {
		Method target = defs[i].equals("wasNull") ? wasNull : ResultSet.class.getMethod(defs[i].toString(), int.class);
		values.put(target, defs[i + 1]);
	}

	AtomicBoolean flg = new AtomicBoolean(false);

	InvocationHandler handler = new InvocationHandler() {

		@Override
		public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
			if (values.containsKey(method)) {
				Object o = values.get(method);
				flg.set(o == null);
				return o;
			}
			if (wasNull.equals(method)) {
				return flg.get();
			}

			return null;
		}
	};
	return (ResultSet) Proxy.newProxyInstance(Helper.class.getClassLoader(), new Class[] { ResultSet.class }, handler);
}
 
Example 33
Project: PackagePlugin   File: MainFrame.java   View source code 5 votes vote down vote up
/**
 * 通过此方法添加的监听将通过代理 调用前显示遮罩
 * <p>
 */
public void initListSelectionListener() {
    InvocationHandler handler2 = new AnnotationInvocationHandler(this, this.getListSelectionListenerImpl());
    ListSelectionListenerImpl cc = this.getListSelectionListenerImpl();
    ListSelectionListener listener = (ListSelectionListener) Proxy.newProxyInstance(cc.getClass().getClassLoader(), cc.getClass().getInterfaces(), handler2);
    dbList.addListSelectionListener(listener);
}
 
Example 34
Project: dremio-oss   File: AnnotationDescriptor.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T proxy(Class<T> interfc, InvocationHandler ih) {
  if (!interfc.isInterface()) {
    throw new IllegalArgumentException("only proxying interfaces: " + interfc);
  }
  return (T)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{ interfc }, ih);
}
 
Example 35
Project: jdk8u-jdk   File: ProxyArrayCalls.java   View source code 5 votes vote down vote up
/**
 * Generate proxy object array of the given size.
 */
Proxy[] genProxies(int size) throws Exception {
    Class proxyClass =
        Proxy.getProxyClass(DummyInterface.class.getClassLoader(),
                new Class[] { DummyInterface.class });
    Constructor proxyCons =
        proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    Object[] consArgs = new Object[] { new DummyHandler() };
    Proxy[] proxies = new Proxy[size];

    for (int i = 0; i < size; i++)
        proxies[i] = (Proxy) proxyCons.newInstance(consArgs);

    return proxies;
}
 
Example 36
Project: OpenJSharp   File: InvocationHandlerFactoryImpl.java   View source code 5 votes vote down vote up
public InvocationHandler getInvocationHandler()
{
    final DynamicStub stub = new DynamicStubImpl(
        classData.getTypeIds() ) ;

    return getInvocationHandler( stub ) ;
}
 
Example 37
Project: apache-tomcat-7.0.73-with-comment   File: StatementDecoratorInterceptor.java   View source code 5 votes vote down vote up
protected Constructor<?> getResultSetConstructor() throws NoSuchMethodException {
    if (resultSetConstructor == null) {
        Class<?> proxyClass = Proxy.getProxyClass(StatementDecoratorInterceptor.class.getClassLoader(),
                new Class[] { ResultSet.class });
        resultSetConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    }
    return resultSetConstructor;
}
 
Example 38
Project: ramus   File: FilePlugin.java   View source code 5 votes vote down vote up
private Object createChangeListener(Class<?> clazz) {
    return Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class<?>[]{clazz}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method,
                                     Object[] args) throws Throwable {
                    changed();
                    return null;
                }
            });
}
 
Example 39
Project: condom   File: CondomProcess.java   View source code 5 votes vote down vote up
@SuppressLint("PrivateApi") private static void installCondomProcessActivityManager(final CondomCore condom)
		throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
	final Class<?> ActivityManagerNative = Class.forName("android.app.ActivityManagerNative");
	Field ActivityManagerNative_gDefault = null;
	if (SDK_INT <= N_MR1) try {
		ActivityManagerNative_gDefault = ActivityManagerNative.getDeclaredField("gDefault");
	} catch (final NoSuchFieldException ignored) {}		// ActivityManagerNative.gDefault is no longer available on Android O.
	if (ActivityManagerNative_gDefault == null) {
		ActivityManagerNative_gDefault = ActivityManager.class.getDeclaredField("IActivityManagerSingleton");
	}
	ActivityManagerNative_gDefault.setAccessible(true);
	final Class<?> Singleton = Class.forName("android.util.Singleton");
	final Method Singleton_get = Singleton.getDeclaredMethod("get");
	Singleton_get.setAccessible(true);
	final Field Singleton_mInstance = Singleton.getDeclaredField("mInstance");
	Singleton_mInstance.setAccessible(true);
	final Class<?> IActivityManager = Class.forName("android.app.IActivityManager");

	final Object/* Singleton */singleton = ActivityManagerNative_gDefault.get(null);
	if (singleton == null) throw new IllegalStateException("ActivityManagerNative.gDefault is null");
	final Object/* IActivityManager */am = Singleton_get.invoke(singleton);
	if (am == null) throw new IllegalStateException("ActivityManagerNative.gDefault.get() returns null");

	final InvocationHandler handler;
	if (Proxy.isProxyClass(am.getClass()) && (handler = Proxy.getInvocationHandler(am)) instanceof CondomProcessActivityManager) {
		Log.w(TAG, "CondomActivityManager was already installed in this process.");
		((CondomProcessActivityManager) handler).mCondom = condom;
	} else {
		final Object condom_am = Proxy.newProxyInstance(condom.mBase.getClassLoader(), new Class[] { IActivityManager },
				new CondomProcessActivityManager(condom, am));
		Singleton_mInstance.set(singleton, condom_am);
	}
}
 
Example 40
Project: container   File: Reflect.java   View source code 5 votes vote down vote up
/**
 * 创建一个动态代理根据传入的类型. 如果我们正在维护的是一个Map,那么当调用出现异常时我们将从Map中取值.
 *
 * @param proxyType 需要动态代理的类型
 * @return 动态代理生成的对象
 */
@SuppressWarnings("unchecked")
public <P> P as(Class<P> proxyType) {
    final boolean isMap = (object instanceof Map);
    final InvocationHandler handler = new InvocationHandler() {
        @Mark
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String name = method.getName();
            try {
                return on(object).call(name, args).get();
            } catch (ReflectException e) {
                if (isMap) {
                    Map<String, Object> map = (Map<String, Object>) object;
                    int length = (args == null ? 0 : args.length);

                    if (length == 0 && name.startsWith("get")) {
                        return map.get(property(name.substring(3)));
                    } else if (length == 0 && name.startsWith("is")) {
                        return map.get(property(name.substring(2)));
                    } else if (length == 1 && name.startsWith("set")) {
                        map.put(property(name.substring(3)), args[0]);
                        return null;
                    }
                }

                throw e;
            }
        }
    };

    return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler);
}