Java Code Examples for java.lang.reflect.Proxy.newProxyInstance()

The following are Jave code examples for showing how to use newProxyInstance() of the java.lang.reflect.Proxy class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Progetto-B   File: Game.java   View Source Code Vote up 8 votes
/**
 * Builds the list of players.
 *
 * @param playersInfo
 */
private void buildPlayers(List<PlayerInfo> playersInfo) {

    Player player;
    for (PlayerInfo info : playersInfo) {
        switch (info.getType()) {
            case "ARTIFICIAL":
                player = new ArtificialPlayer(info.getName(), info.getColor(), (GameProxy) Proxy.newProxyInstance(GameProxy.class.getClassLoader(),
                        new Class<?>[]{GameProxy.class},
                        new GameInvocationHandler(this)));
                this.players.add(player);
                break;
            case "NORMAL":
                this.players.add(new Player(info.getName(), info.getColor()));
                break;
            case "LOGGED":
                this.players.add(new LoggedPlayer(info.getName(), info.getColor()));
                break;
            default:
            //
        }
    }
    Collections.shuffle(players);
}
 
Example 2
Project: LookWeather   File: TestPattern.java   View Source Code Vote up 7 votes
/**
 * 代理模式
 * newProxyInstance 返回接口 调用接口实现类的任何方法都会调用代理模式的invoke
 */
private static void proxy() {
    final ICat cat = new Cat();

    ICat proxyCat=(ICat) Proxy.newProxyInstance(TestPattern.class.getClassLoader(), cat.getClass().getInterfaces(), new InvocationHandler() {
        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            if (method.getName().equals("run")) {
                System.out.println("猫抓老鼠");
                return method.invoke(cat, objects);
            }
            return method.invoke(cat, objects);
        }
    });
    proxyCat.hashCode();
}
 
Example 3
Project: goku-jdbc   File: GokuInvocationHandler.java   View Source Code Vote up 7 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        Object ret = method.invoke(orig, args);
        Class<?> returnType = method.getReturnType();
        if (WRAP_TARGET_CLASSES.contains(returnType)) {
            ret = Proxy.newProxyInstance(returnType.getClassLoader(), new Class[]{returnType},
                    new GokuInvocationHandler(ret));
        }
        return ret;
    } catch (InvocationTargetException ex) {
        Throwable targetEx = ex.getTargetException();
        if (targetEx instanceof SQLException) {
            targetEx = new GokuSQLException((SQLException) targetEx);
        }
        throw targetEx;
    }
}
 
Example 4
Project: netto_rpc   File: ReferenceBean.java   View Source Code Vote up 7 votes
public Object getObject() throws Exception {
	ServiceProvider provider = this.router.findProvider();
	if (this.timeout <= 0) {
		ServiceAPIClient apiClient = new ServiceAPIClient(provider, this, 1000);
		this.timeout = apiClient.getServerTimeout(this.serviceName);
	}
	if (protocol.equals("tcp")) {
		// 需要看看router的注册中心和注入的注册中心是否一致,如果不一致就把协议改为http
		if (provider.getRouteConfig() != null) {
			if (!provider.getServerDesc().getRegistry().equals(provider.getRouteConfig().getTargetRegistry())) {
				protocol = "http";
			}
		}
	}
	InvocationHandler client;
	if (protocol.equals("tcp")) {
		client = new RpcTcpClient(provider, filters, serviceName, this.timeout);
	} else {
		client = new RpcHttpClient(provider, filters, this.serviceName, this.timeout);
	}
	Object proxy = Proxy.newProxyInstance(interfaceClazz.getClassLoader(), new Class<?>[] { interfaceClazz },
			client);
	return proxy;
}
 
Example 5
Project: intellij-deps-ini4j   File: AbstractBeanInvocationHandlerTest.java   View Source Code Vote up 7 votes
@Test public void testMisc() throws Exception
{
    Map<String, String> map = new HashMap<String, String>();
    MapBeanHandler handler = new MapBeanHandler(map);
    Dummy dummy = (Dummy) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Dummy.class }, handler);

    assertNull(handler.getProxy());

    // non existend method calls
    dummy.dummy();
    dummy.addDummy();
    dummy.removeDummy();

    // boolean invoke
    map.put("dummy", "true");
    assertTrue(dummy.isDummy());
    assertSame(dummy, handler.getProxy());

    // subclass should call fire methods any time
    // so null support reference should be not a problem
    handler.firePropertyChange(PROP_AGE, Integer.valueOf(1), Integer.valueOf(2));
    handler.fireVetoableChange(PROP_AGE, Integer.valueOf(1), Integer.valueOf(2));
}
 
Example 6
Project: APacheSynapseSimplePOC   File: JRMPClient.java   View Source Code Vote up 7 votes
public Registry getObject ( final String command ) throws Exception {

        String host;
        int port;
        int sep = command.indexOf(':');
        if ( sep < 0 ) {
            port = new Random().nextInt(65535);
            host = command;
        }
        else {
            host = command.substring(0, sep);
            port = Integer.valueOf(command.substring(sep + 1));
        }
        ObjID id = new ObjID(new Random().nextInt()); // RMI registry
        TCPEndpoint te = new TCPEndpoint(host, port);
        UnicastRef ref = new UnicastRef(new LiveRef(id, te, false));
        RemoteObjectInvocationHandler obj = new RemoteObjectInvocationHandler(ref);
        Registry proxy = (Registry) Proxy.newProxyInstance(JRMPClient.class.getClassLoader(), new Class[] {
            Registry.class
        }, obj);
        return proxy;
    }
 
Example 7
Project: lams   File: AbstractFactoryBean.java   View Source Code Vote up 6 votes
/**
 * Determine an 'eager singleton' instance, exposed in case of a
 * circular reference. Not called in a non-circular scenario.
 */
@SuppressWarnings("unchecked")
private T getEarlySingletonInstance() throws Exception {
	Class<?>[] ifcs = getEarlySingletonInterfaces();
	if (ifcs == null) {
		throw new FactoryBeanNotInitializedException(
				getClass().getName() + " does not support circular references");
	}
	if (this.earlySingletonInstance == null) {
		this.earlySingletonInstance = (T) Proxy.newProxyInstance(
				this.beanClassLoader, ifcs, new EarlySingletonInvocationHandler());
	}
	return this.earlySingletonInstance;
}
 
Example 8
Project: ProyectoPacientes   File: JDBC4PreparedStatementWrapper.java   View Source Code Vote up 6 votes
/**
 * Returns an object that implements the given interface to allow access to
 * non-standard methods, or standard methods not exposed by the proxy. The
 * result may be either the object found to implement the interface or a
 * proxy for that object. If the receiver implements the interface then that
 * is the object. If the receiver is a wrapper and the wrapped object
 * implements the interface then that is the object. Otherwise the object is
 * the result of calling <code>unwrap</code> recursively on the wrapped
 * object. If the receiver is not a wrapper and does not implement the
 * interface, then an <code>SQLException</code> is thrown.
 * 
 * @param iface
 *            A Class defining an interface that the result must implement.
 * @return an object that implements the interface. May be a proxy for the
 *         actual implementing object.
 * @throws java.sql.SQLException
 *             If no object found that implements the interface
 * @since 1.6
 */
public synchronized <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
    try {
        if ("java.sql.Statement".equals(iface.getName()) || "java.sql.PreparedStatement".equals(iface.getName())
                || "java.sql.Wrapper.class".equals(iface.getName())) {
            return iface.cast(this);
        }

        if (unwrappedInterfaces == null) {
            unwrappedInterfaces = new HashMap<Class<?>, Object>();
        }

        Object cachedUnwrapped = unwrappedInterfaces.get(iface);

        if (cachedUnwrapped == null) {
            if (cachedUnwrapped == null) {
                cachedUnwrapped = Proxy.newProxyInstance(this.wrappedStmt.getClass().getClassLoader(), new Class<?>[] { iface },
                        new ConnectionErrorFiringInvocationHandler(this.wrappedStmt));
                unwrappedInterfaces.put(iface, cachedUnwrapped);
            }
            unwrappedInterfaces.put(iface, cachedUnwrapped);
        }

        return iface.cast(cachedUnwrapped);
    } catch (ClassCastException cce) {
        throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
    }
}
 
Example 9
Project: openjdk-jdk10   File: ProxyTest.java   View Source Code Vote up 6 votes
private static void testProxyClass(Module module, ClassLoader ld, Class<?>... interfaces) {
    Class<?> proxyClass = Proxy.getProxyClass(ld, interfaces);
    assertEquals(proxyClass.getModule(), module);

    Object proxy = Proxy.newProxyInstance(ld, interfaces, handler);
    assertEquals(proxy.getClass().getModule(), module);
}
 
Example 10
Project: monarch   File: DiskInitFileParser.java   View Source Code Vote up 6 votes
private static DiskInitFileInterpreter createPrintingInterpreter(
    DiskInitFileInterpreter wrapped) {
  DiskInitFileInterpreter interpreter = (DiskInitFileInterpreter) Proxy.newProxyInstance(
      DiskInitFileInterpreter.class.getClassLoader(), new Class[] {DiskInitFileInterpreter.class},
      new PrintingInterpreter(wrapped));
  return interpreter;
}
 
Example 11
Project: ditb   File: HbaseHandlerMetricsProxy.java   View Source Code Vote up 6 votes
public static Hbase.Iface newInstance(Hbase.Iface handler,
                                      ThriftMetrics metrics,
                                      Configuration conf) {
  return (Hbase.Iface) Proxy.newProxyInstance(
      handler.getClass().getClassLoader(),
      new Class[]{Hbase.Iface.class},
      new HbaseHandlerMetricsProxy(handler, metrics, conf));
}
 
Example 12
Project: hadoop   File: RootDocProcessor.java   View Source Code Vote up 6 votes
private static Object getProxy(Object obj) { 
  Object proxy = proxies.get(obj); 
  if (proxy == null) { 
    proxy = Proxy.newProxyInstance(obj.getClass().getClassLoader(), 
      obj.getClass().getInterfaces(), new ExcludeHandler(obj)); 
    proxies.put(obj, proxy); 
  } 
  return proxy; 
}
 
Example 13
Project: openjdk-jdk10   File: ProxyModuleMapping.java   View Source Code Vote up 6 votes
void verifyNewProxyInstance() throws Exception {
    Object o = Proxy.newProxyInstance(loader, interfaces, ih);
    Module m = o.getClass().getModule();
    if (target != null && m != target) {
        throw new RuntimeException(m + " not expected: " + target);
    }
    if (target == null && (!m.isNamed() || !m.getName().startsWith("jdk.proxy"))) {
        throw new RuntimeException(m + " not expected: dynamic module");
    }
}
 
Example 14
Project: VirtualHook   File: Reflect.java   View Source Code Vote up 6 votes
/**
 * 创建一个动态代理根据传入的类型. 如果我们正在维护的是一个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);
}
 
Example 15
Project: Progetto-B   File: GUI.java   View Source Code Vote up 5 votes
/**
 * Initializes the GUI and it creates the game.
 */
private void init(List<PlayerInfo> players) {

    // Image fading out
    fadeOutLabel = new FadeOutLabel(this);
    fadeOutLabel.setOpaque(true);
    fadeOutLabel.setBounds(334, 233, 332, 46);
    mapLayeredPane.add(fadeOutLabel, 1000);

    // Labels
    initLabels();
    ((GraphicsJLabel) labelMap).setCountryLabel(countryLabelMap);
    mapLayeredPane.setComponentZOrder(labelMap, mapLayeredPane.getComponentCount() - 1);
    textAreaInfo.setText("Clicca su un tuo territorio per rinforzarlo con 1 armata");
    textAreaInfo.setBackground(new Color(0, 0, 0, 100));
    updatePlayersOrder(players);

    // Mouse Listeners
    labelMapListener = new LabelMapListener(labelMap, colorCountryNameMap, this);
    labelMap.addMouseListener(labelMapListener);
    labelMap.addMouseMotionListener(labelMapListener);

    // Game
    game = (GameProxy) Proxy.newProxyInstance(GameProxy.class.getClassLoader(),
            new Class<?>[]{GameProxy.class},
            new GameInvocationHandler(new Game(players, this)));
    labelMapListener.setGame(game);

    // Dialogs
    defenseDialog = new DefenseDialog(game, this, true);
    attackerDialog = new AttackerDialog(game, this, true);
    attackerDialog.setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
    diceDialog = new DiceDialog(game, this, true);

    // CardPanel
    cardPanel = new CardPanel(game);
    this.add(cardPanel, 0);
    cardPanel.setBounds(10, 530, 1200, 300);
    cardPanel.setOpaque(false);
    // Setting
    Dimension dim = getToolkit().getScreenSize();
    this.setLocation(dim.width / 2 - this.getWidth() / 2, dim.height / 2 - this.getHeight() / 2);

    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            closeDialog();
        }
    });

}
 
Example 16
Project: Reer   File: TestNGListenerAdapterFactory.java   View Source Code Vote up 5 votes
private ITestListener createProxy(Class<?> configListenerClass, final ITestListener listener) {
    Class<?>[] interfaces = new Class<?>[]{ITestListener.class, ISuiteListener.class, configListenerClass};
    return (ITestListener) Proxy.newProxyInstance(classLoader, interfaces, new AdaptedListener(listener));
}
 
Example 17
Project: dubbox-hystrix   File: JdkProxyFactory.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
    return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker));
}
 
Example 18
Project: alfresco-repository   File: AJProxyTrait.java   View Source Code Vote up 4 votes
/**
 * {@link Trait} {@link Proxy} factory method.
 * 
 * @param extensible the {@link Extensible} object that defines the given
 *            {@link Trait}
 * @param traitAPI the trait interface part that the given
 *            {@link Extensible} object defines
 * @return a {@link Proxy} object for the given trait API interface with an
 *         {@link AJProxyTrait} attached. All method calls performed on the
 *         returned proxy will be delegated to a given {@link Extensible}
 *         object method having the same signature within an
 *         {@link ExtensionBypass} context.
 */
@SuppressWarnings("unchecked")
public static <M extends Trait> M create(Object extensibleInterface, Class<M> traitAPI)
{
    return (M) Proxy.newProxyInstance(AJProxyTrait.class.getClassLoader(),
                                      new Class[] { traitAPI },
                                      new AJProxyTrait(extensibleInterface));
}
 
Example 19
Project: restclient   File: RestConfig.java   View Source Code Vote up 4 votes
/**
 * 获取实例
 * 
 * @param apiClass
 *            接口类
 * @param basedir
 *            模板路径
 * @return 实例
 */
public static <T> T getBean(Class<T> apiClass, String basedir) {
    if (apiClass.isInterface()) {
        return (T) Proxy.newProxyInstance(RestConfig.class.getClassLoader(), new Class<?>[] { apiClass }, new IfaceProxy(basedir));
    } else {
        throw new RuntimeException(apiClass.getName() + "is not isInterface");
    }
}
 
Example 20
Project: lams   File: JdbcTemplate.java   View Source Code Vote up 4 votes
/**
 * Create a close-suppressing proxy for the given JDBC Connection.
 * Called by the {@code execute} method.
 * <p>The proxy also prepares returned JDBC Statements, applying
 * statement settings such as fetch size, max rows, and query timeout.
 * @param con the JDBC Connection to create a proxy for
 * @return the Connection proxy
 * @see java.sql.Connection#close()
 * @see #execute(ConnectionCallback)
 * @see #applyStatementSettings
 */
protected Connection createConnectionProxy(Connection con) {
	return (Connection) Proxy.newProxyInstance(
			ConnectionProxy.class.getClassLoader(),
			new Class<?>[] {ConnectionProxy.class},
			new CloseSuppressingInvocationHandler(con));
}