List of usage examples for java.lang.reflect Proxy newProxyInstance
private static Object newProxyInstance(Class<?> caller, Constructor<?> cons, InvocationHandler h)
From source file:org.eclipse.wb.internal.rcp.model.rcp.ViewPartLikeInfo.java
/** * Prepares {@link IActionBars} instance, with {@link ToolBarManager} and {@link MenuManager}. *//* w ww . j a va2s. co m*/ private void prepareActionBars() throws Exception { ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this); Class<?> toolBarManagerClass = editorLoader.loadClass("org.eclipse.jface.action.ToolBarManager"); Class<?> menuManagerClass = editorLoader.loadClass("org.eclipse.jface.action.MenuManager"); Class<?> actionBarsClass = editorLoader.loadClass("org.eclipse.ui.IActionBars"); // create managers m_toolBarManager = toolBarManagerClass.newInstance(); m_menuManager = menuManagerClass.newInstance(); // create IActionBars m_actionBars = Proxy.newProxyInstance(editorLoader, new Class<?>[] { actionBarsClass }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (ReflectionUtils.getMethodSignature(method).equals("getToolBarManager()")) { return m_toolBarManager; } if (ReflectionUtils.getMethodSignature(method).equals("getMenuManager()")) { return m_menuManager; } throw new NotImplementedException(); } }); }
From source file:org.aludratest.maven.surefire.AludraTestSurefireProvider.java
@Override public RunResult invoke(Object forkTestSet) throws TestSetFailedException, ReporterException, InvocationTargetException { if (forkTestSet != null) { throw new IllegalArgumentException( "AludraTest Surefire Provider does not expect forkTestSet parameter"); }/*from w ww . ja v a 2 s .co m*/ RunListener reporter = reporterFactory.createReporter(); // check direct test request first String directTest = testRequest.getRequestedTest(); String directTestMethod = testRequest.getRequestedTestMethod(); if (directTest != null) { directTest = directTest.trim(); while (directTest.endsWith(",")) { directTest = directTest.substring(0, directTest.length() - 1); directTest = directTest.trim(); } Class<?> classToTest = ReflectionUtils.tryLoadClass(testClassLoader, directTest); if (classToTest == null) { throw new IllegalArgumentException("Class " + directTest + " not found in test scope"); } // startup AludraTest Framework Object aludraTest = AludraTestReflectionUtil.startFramework(testClassLoader); try { // create our very own RunnerListener Class<?> runnerListenerClass = testClassLoader.loadClass(RunnerListener.class.getName()); AludraTestReportListener reportListener = new AludraTestReportListener(reporter); Object runnerListenerProxy = Proxy.newProxyInstance(testClassLoader, new Class<?>[] { runnerListenerClass }, reportListener); // register it to RunnerListenerRegistry AludraTestReflectionUtil.registerRunnerListener(runnerListenerProxy, aludraTest, runnerListenerClass); AludraTestReflectionUtil.runAludraTest(aludraTest, classToTest); // extract results from listener return reportListener.createRunResult(); } catch (ClassNotFoundException e) { throw new InvocationTargetException(e); } finally { AludraTestReflectionUtil.stopFramework(aludraTest); } } else if (directTestMethod != null) { // TODO support for method only invocation throw new TestSetFailedException("Running AludraTest test methods currently not supported (" + directTestMethod + " cannot be executed)"); } else { if (testsToRun == null) { // if (forkTestSet instanceof TestsToRun) { // testsToRun = (TestsToRun) forkTestSet; // } // else if (forkTestSet instanceof Class) { // testsToRun = TestsToRun.fromClass((Class<?>) forkTestSet); // } // else { testsToRun = scanClassPath(); // } } throw new TestSetFailedException( "Running multiple AludraTest test classes currently not supported. Please use -Dtest=<testOrSuiteClass>"); } }
From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java
private <T> T createEntityManagerProxy(Class<T> interfaceClass, Object emProxy) { InvocationHandler handler = (proxy, method, args) -> { EntityManager em = entityManagerLocal.get() != null ? entityManagerLocal.get() : (EntityManager) emProxy; switch (method.getName()) { case "hashCode": return hashCode(); case "equals": return (em == args[0]); case "toString": return "Camel EntityManager proxy [" + em.toString() + "]"; }//from w w w. j av a2 s . c o m if (!em.isJoinedToTransaction()) { em.joinTransaction(); } return method.invoke(em, args); }; return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, handler); }
From source file:org.alfresco.traitextender.SingletonExtensionFactory.java
@SuppressWarnings("unchecked") @Override// w w w . ja v a2s .c o m public <TO extends Trait> E createExtension(TO traitObject) { T tTrait = (T) traitObject; // perform programmatic RTTI if (!singleton.acceptsTrait(traitObject)) { throw new InvalidExtension( "Extension factory error : " + singleton.getClass() + " does not support trait " + traitObject); } if (logger.isDebugEnabled()) { String traitTrace = traitObject != null ? traitObject.getClass().toString() : "<null> trait"; logger.info("Creating singleton extension " + singleton.getClass() + "<-" + traitTrace); } else { logger.info("Creating singleton extension " + singleton.getClass()); } return (E) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { extensionAPI }, new TraiSingletontHandler(singleton, tTrait)); }
From source file:org.seedstack.spring.internal.SeedInstanceFactoryBean.java
@Override public Object getObject() throws Exception { if (classname == null) { throw new IllegalArgumentException("Property classname is required for SeedFactoryBean"); } else {/*from ww w . j a v a2s . c o m*/ Class<?> instanceClass = Class.forName(classname); if (proxy) { // delay underlying instance retrieving via proxy to break circular dependencies problems return Proxy.newProxyInstance(SeedInstanceFactoryBean.class.getClassLoader(), new Class<?>[] { instanceClass }, new InstanceProxy(instanceClass, qualifier)); } else { return createInstance(instanceClass, qualifier); } } }
From source file:net.sourceforge.pmd.lang.java.ParserTstUtil.java
public static ASTCompilationUnit buildDFA(String javaCode) { LanguageVersionHandler languageVersionHandler = LanguageRegistry.getLanguage(JavaLanguageModule.NAME) .getDefaultVersion().getLanguageVersionHandler(); ASTCompilationUnit cu = (ASTCompilationUnit) languageVersionHandler .getParser(languageVersionHandler.getDefaultParserOptions()) .parse(null, new StringReader(javaCode)); JavaParserVisitor jpv = (JavaParserVisitor) Proxy.newProxyInstance(JavaParserVisitor.class.getClassLoader(), new Class[] { JavaParserVisitor.class }, new Collector<>(ASTCompilationUnit.class)); jpv.visit(cu, null);/*ww w . j av a2s . com*/ new SymbolFacade().initializeWith(cu); new DataFlowFacade().initializeWith(languageVersionHandler.getDataFlowHandler(), cu); return cu; }
From source file:org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator.java
@SuppressWarnings("unchecked") public <T> T decorate(String registrationPoint, Class<T> targetClass, T listener) { if (listener instanceof InternalListener || !isSupported(listener)) { return listener; }/*from w ww .jav a 2 s . c o m*/ UserCodeApplicationId applicationId = userCodeApplicationContext.current(); if (applicationId == null) { return listener; } Class<?> listenerClass = listener.getClass(); List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(listenerClass); BuildOperationEmittingInvocationHandler handler = new BuildOperationEmittingInvocationHandler(applicationId, registrationPoint, listener); return targetClass.cast(Proxy.newProxyInstance(listenerClass.getClassLoader(), allInterfaces.toArray(new Class[0]), handler)); }
From source file:net.big_oh.common.jdbc.JdbcObserverProxyConnectionInvocationHandler.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // intercept calls that create statements if (Statement.class.isAssignableFrom(method.getReturnType())) { StatementInstantiationEvent event = new StatementInstantiationEvent((Connection) proxy); for (JDBCEventListener listener : listeners) { try { listener.statementRequested(event); } catch (RuntimeException rte) { logger.error(rte);//from ww w. ja va 2 s. c o m } } Statement newStatement = (Statement) method.invoke(originalConnection, args); // Create proxy for the returned statement object String hardCodedSqlForStatement = (newStatement instanceof PreparedStatement && args != null && args.length > 0 && args[0] instanceof String) ? args[0].toString() : null; boolean newStatementInterfacesContainsMethodReturnTypeClass = Arrays .asList(newStatement.getClass().getInterfaces()).contains(method.getReturnType()); Class<?>[] interfaces = new Class<?>[(newStatement.getClass().getInterfaces().length + ((newStatementInterfacesContainsMethodReturnTypeClass) ? 0 : 1))]; System.arraycopy(newStatement.getClass().getInterfaces(), 0, interfaces, 0, newStatement.getClass().getInterfaces().length); if (!newStatementInterfacesContainsMethodReturnTypeClass) { interfaces[newStatement.getClass().getInterfaces().length] = method.getReturnType(); } Statement statementProxy = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(), interfaces, new JdbcObserverProxyStatementInvocationHandler(newStatement, listeners, hardCodedSqlForStatement)); for (JDBCEventListener listener : listeners) { try { listener.statementInstantiated(event, statementProxy); } catch (RuntimeException rte) { logger.error(rte); } } return statementProxy; } // otherwise, just invoke the method on the underlying // originalConnection return method.invoke(originalConnection, args); }
From source file:cc.creativecomputing.events.CCListenerManager.java
/** * Creates an EventListenerSupport object which supports the provided listener interface using the specified class * loader to create the JDK dynamic proxy. * /*www. j a va2s . c o m*/ * @param listenerInterface the listener interface. * @param classLoader the class loader. * * @throws NullPointerException if <code>listenerInterface</code> or <code>classLoader</code> is <code>null</code>. * @throws IllegalArgumentException if <code>listenerInterface</code> is not an interface. */ public CCListenerManager(Class<ListenerType> listenerInterface, ClassLoader classLoader) { Validate.notNull(listenerInterface, "Listener interface cannot be null."); Validate.notNull(classLoader, "ClassLoader cannot be null."); Validate.isTrue(listenerInterface.isInterface(), "Class {0} is not an interface", listenerInterface.getName()); _myProxy = listenerInterface.cast(Proxy.newProxyInstance(classLoader, new Class[] { listenerInterface }, new ProxyInvocationHandler())); }
From source file:org.hyperic.hq.agent.client.AbstractCommandsClient.java
/** * Retrieve a synchronous proxy to a remote service. * //from w w w. j av a 2 s .com * @param serviceInterface The service interface. It is expected that all * service interface operations throw an * {@link AgentRemoteException}. * @return The synchronous proxy. * @throws AgentConnectionException if there is an error creating the proxy. * @throws IllegalArgumentException if any of the service interface operations * do not throw an {@link AgentRemoteException}. */ protected final Object getSynchronousProxy(Class serviceInterface) throws AgentConnectionException { TransportUtils.assertOperationsThrowException(serviceInterface, AgentRemoteException.class); Object proxy; try { proxy = _factory.createSyncService(_agent, serviceInterface); } catch (Exception e) { _log.error("Error creating proxy to remote service.", e); throw new AgentConnectionException("Error creating proxy to remote service.", e); } if (_agent.isUnidirectional()) { // For unidirectional agents, if a synchronous request blocks for // more than the specified timeout (see ResponseHandler#RESPONSE_WAIT_TIME) // waiting for the response, then a TimeoutException is thrown. This // exception will be wrapped in an HQ-specific checked exception // (AgentRemoteException). final InvocationHandler handler = Proxy.getInvocationHandler(proxy); InvocationHandler timeoutExceptionHandler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return handler.invoke(proxy, method, args); } catch (TimeoutException e) { throw new AgentRemoteException("Timeout occurred waiting on agent response.", e); } } }; proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { serviceInterface }, timeoutExceptionHandler); } return proxy; }