All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.snapscript.bridge.standard.EnhancerGenerator Maven / Gradle / Ivy

There is a newer version: 1.4.6
Show newest version
package org.snapscript.bridge.standard;

import org.snapscript.bridge.generate.ClassGenerator;
import org.snapscript.cglib.proxy.Enhancer;
import org.snapscript.cglib.proxy.MethodInterceptor;
import org.snapscript.common.Cache;
import org.snapscript.common.CopyOnWriteCache;
import org.snapscript.core.Scope;
import org.snapscript.core.convert.InterfaceCollector;

public class EnhancerGenerator implements ClassGenerator {

   private final InterfaceCollector collector;
   private final Cache cache;
   
   public EnhancerGenerator(Class... interfaces) {
      this.collector = new InterfaceCollector(interfaces);
      this.cache = new CopyOnWriteCache();      
   }
   
   @Override
   public Class generate(Scope scope, Class type) {
      Class proxy = cache.fetch(type);
      
      if(proxy == null) {
         proxy = create(scope, type);
         cache.cache(type, proxy);
      }
      return proxy;
   }
   
   private Class create(Scope scope, Class type) {
      Class[] types = collector.collect(scope);
      
      try {
         Class[] handlers = new Class[] {MethodInterceptor.class};
         Enhancer enhancer = new Enhancer();
         
         enhancer.setSuperclass(type);
         enhancer.setInterfaces(types); // ensure we can convert from object to Instance
         enhancer.setCallbackTypes(handlers);
         
         return enhancer.createClass();
      } catch(Exception e) {
         throw new IllegalStateException("Could not create proxy for " + type, e);
      }
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy