Package javassist.util.proxy

Examples of javassist.util.proxy.ProxyFactory

Here, Method is java.lang.reflect.Method.

Then, the following method call will be forwarded to MethodHandler mi and prints a message before executing the originally called method bar() in Foo.

The last three lines of the code shown above can be replaced with a call to the helper method create, which generates a proxy class, instantiates it, and sets the method handler of the instance:

To change the method handler during runtime, execute the following code:

If setHandler is never called for a proxy instance then it will employ the default handler which proceeds by invoking the original method. The behaviour of the default handler is identical to the following handler:

A proxy factory caches and reuses proxy classes by default. It is possible to reset this default globally by setting static field {@link ProxyFactory#useCache} to false.Caching may also be configured for a specific factory by calling instance method {@link ProxyFactory#setUseCache(boolean)}. It is strongly recommended that new clients of class ProxyFactory enable caching. Failure to do so may lead to exhaustion of the heap memory area used to store classes.

Caching is automatically disabled for any given proxy factory if deprecated instance method {@link ProxyFactory#setHandler(MethodHandler)} is called. This method wasused to specify a default handler which newly created proxy classes should install when they create their instances. It is only retained to provide backward compatibility with previous releases of javassist. Unfortunately,this legacy behaviour makes caching and reuse of proxy classes impossible. The current programming model expects javassist clients to set the handler of a proxy instance explicitly by calling method {@link Proxy#setHandler(MethodHandler)} as shown in the sample code above. Newclients are strongly recommended to use this model rather than calling {@link ProxyFactory#setHandler(MethodHandler)}.

A proxy object generated by ProxyFactory is serializable if its super class or any of its interfaces implement java.io.Serializable. However, a serialized proxy object may not be compatible with future releases. The serialization support should be used for short-term storage or RMI.

For compatibility with older releases serialization of proxy objects is implemented by adding a writeReplace method to the proxy class. This allows a proxy to be serialized to a conventional {@link java.io.ObjectOutputStream} and deserialized from a corresponding{@link java.io.ObjectInputStream}. However this method suffers from several problems, the most notable one being that it fails to serialize state inherited from the proxy's superclass.

An alternative method of serializing proxy objects is available which fixes these problems. It requires inhibiting generation of the writeReplace method and instead using instances of {@link javassist.util.proxy.ProxyObjectOutputStream} and {@link javassist.util.proxy.ProxyObjectInputStream}(which are subclasses of {@link java.io.ObjectOutputStream} and {@link java.io.ObjectInputStream}) to serialize and deserialize, respectively, the proxy. These streams recognise javassist proxies and ensure that they are serialized and deserialized without the need for the proxy class to implement special methods such as writeReplace. Generation of the writeReplace method can be disabled globally by setting static field {@link ProxyFactory#useWriteReplace} to false. Alternatively, it may beconfigured per factory by calling instance method {@link ProxyFactory#setUseWriteReplace(boolean)}. @see MethodHandler @since 3.1 @author Muga Nishizawa @author Shigeru Chiba @author Andrew Dinn


  private JavassistDataObjectInstantiator() {
  }

  public <T> T newInstance(Class<T> classToInstantiate) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass(classToInstantiate);
    Class newClass = proxyFactory.createClass();
    Object instance;
    try {
      instance = newClass.newInstance();
    } catch (Exception e) {
      throw new MappingException(e);
View Full Code Here


         socket.setEnabledProtocols(protocols);
      if (cipherSuites != null)
         socket.setEnabledCipherSuites(cipherSuites);

      DomainServerSocket handler = new DomainServerSocket(socket);
      ProxyFactory pf = new ProxyFactory();
      pf.setHandler(handler);
      pf.setSuperclass(SSLServerSocket.class);
      Class[] sig = {};
      Object[] args = {};

      SSLServerSocket proxy = null;
      try
      {
         proxy = (SSLServerSocket) pf.create(sig, args);
      }
      catch (Exception e)
      {
         IOException ioe = new IOException("Failed to create SSLServerSocket proxy");
         ioe.initCause(e);
View Full Code Here

         socket.setEnabledProtocols(protocols);
      if( cipherSuites != null )
         socket.setEnabledCipherSuites(cipherSuites);

      DomainServerSocket handler = new DomainServerSocket(socket);
      ProxyFactory pf = new ProxyFactory();
      pf.setHandler(handler);
      pf.setSuperclass(SSLServerSocket.class);
      Class[] sig = {};
      Object[] args = {};

      SSLServerSocket proxy = null;
      try
      {
         proxy = (SSLServerSocket) pf.create(sig, args);
      }
      catch (Exception e)
      {
         IOException ioe = new IOException("Failed to create SSLServerSocket proxy");
         ioe.initCause(e);
View Full Code Here

  @Override
  @SuppressWarnings("unchecked")
  public <G extends GlobalContext<?, ?>> G createGlobalContext(Class<? extends G> globalContextImplType,
      final Class<? extends EntityContext<?, ?>> entityContextImplType, Class<? extends PropertyContext<?, ?>> propertyContextImplType) {

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass( globalContextImplType );
    proxyFactory.setFilter( new EntityMethodFilter() );

    try {
      return (G) proxyFactory.create(
          new Class<?>[] { ConfigurationContext.class },
          new Object[] { this },
          new EntityOrPropertyMethodHandler( entityContextImplType, propertyContextImplType ) );
    }
    catch (Exception e) {
View Full Code Here

  @SuppressWarnings("unchecked")
  private <E extends EntityContext<?, ?>> E createEntityMappingContext(Class<? extends E> entityContextImplType,
      Class<? extends PropertyContext<?, ?>> propertyContextImplType) {

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass( entityContextImplType );
    proxyFactory.setFilter( new EntityOrPropertyMethodFilter() );

    try {
      return (E) proxyFactory.create(
          new Class<?>[] { ConfigurationContext.class },
          new Object[] { this },
          new EntityOrPropertyMethodHandler( entityContextImplType, propertyContextImplType ) );
    }
    catch (Exception e) {
View Full Code Here

  @SuppressWarnings("unchecked")
  private <P extends PropertyContext<?, ?>> P createPropertyMappingContext(Class<? extends EntityContext<?, ?>> entityContextImplType,
      Class<? extends P> propertyContextImplType) {

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass( propertyContextImplType );
    proxyFactory.setFilter( new EntityOrPropertyMethodFilter() );

    try {
      return (P) proxyFactory.create(
          new Class<?>[] { ConfigurationContext.class },
          new Object[] { this },
          new EntityOrPropertyMethodHandler( entityContextImplType, propertyContextImplType ) );
    }
    catch (Exception e) {
View Full Code Here

   */
  @SuppressWarnings("unchecked")
  public <G extends GlobalContext<?, ?>> G createGlobalContext(Class<? extends G> globalContextImplType,
      final Class<? extends EntityContext<?, ?>> entityContextImplType, Class<? extends PropertyContext<?, ?>> propertyContextImplType) {

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass( globalContextImplType );
    proxyFactory.setFilter( new EntityMethodFilter() );

    try {
      return (G) proxyFactory.create(
          new Class<?>[] { ConfigurationContext.class },
          new Object[] { this },
          new EntityOrPropertyMethodHandler( entityContextImplType, propertyContextImplType ) );
    }
    catch (Exception e) {
View Full Code Here

  @SuppressWarnings("unchecked")
  private <E extends EntityContext<?, ?>> E createEntityMappingContext(Class<? extends E> entityContextImplType,
      Class<? extends PropertyContext<?, ?>> propertyContextImplType) {

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass( entityContextImplType );
    proxyFactory.setFilter( new EntityOrPropertyMethodFilter() );

    try {
      return (E) proxyFactory.create(
          new Class<?>[] { ConfigurationContext.class },
          new Object[] { this },
          new EntityOrPropertyMethodHandler( entityContextImplType, propertyContextImplType ) );
    }
    catch (Exception e) {
View Full Code Here

  @SuppressWarnings("unchecked")
  private <P extends PropertyContext<?, ?>> P createPropertyMappingContext(Class<? extends EntityContext<?, ?>> entityContextImplType,
      Class<? extends P> propertyContextImplType) {

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass( propertyContextImplType );
    proxyFactory.setFilter( new EntityOrPropertyMethodFilter() );

    try {
      return (P) proxyFactory.create(
          new Class<?>[] { ConfigurationContext.class },
          new Object[] { this },
          new EntityOrPropertyMethodHandler( entityContextImplType, propertyContextImplType ) );
    }
    catch (Exception e) {
View Full Code Here

  }

  public static TaskInputOutputContext getTaskIOContext(
      final Broadcast<Configuration> conf,
      final Accumulator<Map<String, Long>> counters) {
    ProxyFactory factory = new ProxyFactory();
    Class<TaskInputOutputContext> superType = TaskInputOutputContext.class;
    Class[] types = new Class[0];
    Object[] args = new Object[0];
    final TaskAttemptID taskAttemptId = new TaskAttemptID();
    if (superType.isInterface()) {
      factory.setInterfaces(new Class[] { superType });
    } else {
      types = new Class[] { Configuration.class, TaskAttemptID.class, RecordWriter.class, OutputCommitter.class,
          StatusReporter.class };
      args = new Object[] { conf.value(), taskAttemptId, null, null, null };
      factory.setSuperclass(superType);
    }

    final Set<String> handledMethods = ImmutableSet.of("getConfiguration", "getCounter",
        "progress", "getTaskAttemptID");
    factory.setFilter(new MethodFilter() {
      @Override
      public boolean isHandled(Method m) {
        return handledMethods.contains(m.getName());
      }
    });
    MethodHandler handler = new MethodHandler() {
      @Override
      public Object invoke(Object arg0, Method m, Method arg2, Object[] args) throws Throwable {
        String name = m.getName();
        if ("getConfiguration".equals(name)) {
          return conf.value();
        } else if ("progress".equals(name)) {
          // no-op
          return null;
        } else if ("getTaskAttemptID".equals(name)) {
          return taskAttemptId;
        } else if ("getCounter".equals(name)){ // getCounter
          if (args.length == 1) {
            return getCounter(counters, args[0].getClass().getName(), ((Enum) args[0]).name());
          } else {
            return getCounter(counters, (String) args[0], (String) args[1]);
          }
        } else {
          throw new IllegalStateException("Unhandled method " + name);
        }
      }
    };

    try {
      Object newInstance = factory.create(types, args, handler);
      return (TaskInputOutputContext<?, ?, ?, ?>) newInstance;
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
View Full Code Here

TOP

Related Classes of javassist.util.proxy.ProxyFactory

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.