org.objenesis.instantiator.ObjectInstantiator Java Examples

The following examples show how to use org.objenesis.instantiator.ObjectInstantiator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CglibProxy.java    From festival with Apache License 2.0 6 votes vote down vote up
@Override
public Object getProxy(ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(classLoader);
    enhancer.setCallbackType(MethodInterceptor.class);

    Class<?> targetClass = support.getBeanClass();
    enhancer.setSuperclass(targetClass);
    enhancer.setInterfaces(new Class[]{FestivalProxy.class, TargetClassAware.class});
    Class<?> proxyClass = enhancer.createClass();

    Objenesis objenesis = new ObjenesisStd();
    ObjectInstantiator<?> instantiator = objenesis.getInstantiatorOf(proxyClass);
    Object proxyInstance = instantiator.newInstance();

    ((Factory) proxyInstance).setCallbacks(new Callback[]{new CglibMethodInterceptor(support)});

    return proxyInstance;
}
 
Example #2
Source File: ShillelaghUtil.java    From shillelagh with Apache License 2.0 6 votes vote down vote up
/**
 * Takes a class type and constructs it. If the class does not have an empty constructor this
 * will
 * find the parametrized constructor and use nulls and default values to construct the class.
 *
 * @param clazz The class to construct.
 * @param <T> The type of the class to construct.
 * @return The constructed object.
 */
@SuppressWarnings("unchecked")
public static <T> T createInstance(Class<T> clazz) {
  if (clazz.isInterface()) {
    if (clazz == List.class) {
      return (T) new ArrayList();
    } else if (clazz == Map.class) {
      return (T) new HashMap();
    }

    throw new UnsupportedOperationException("Interface types can not be instantiated.");
  }

  ObjectInstantiator instantiator = OBJENESIS.getInstantiatorOf(clazz);
  return (T) instantiator.newInstance();
}
 
Example #3
Source File: MagicInstantiator.java    From objenesis with Apache License 2.0 6 votes vote down vote up
private ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
   String suffix = type.getSimpleName();
   String className = getClass().getName() + "$$$" + suffix;

   Class<ObjectInstantiator<T>> clazz = ClassUtils.getExistingClass(getClass().getClassLoader(), className);

   if(clazz == null) {
      byte[] classBytes = writeExtendingClass(type, className);

      try {
         clazz = ClassDefinitionUtils.defineClass(className, classBytes, type, getClass().getClassLoader());
      } catch (Exception e) {
         throw new ObjenesisException(e);
      }
   }

   return ClassUtils.newInstance(clazz);
}
 
Example #4
Source File: ObjenesisBase.java    From objenesis with Apache License 2.0 6 votes vote down vote up
/**
 * Will pick the best instantiator for the provided class. If you need to create a lot of
 * instances from the same class, it is way more efficient to create them from the same
 * ObjectInstantiator than calling {@link #newInstance(Class)}.
 *
 * @param clazz Class to instantiate
 * @return Instantiator dedicated to the class
 */
@SuppressWarnings("unchecked")
public <T> ObjectInstantiator<T> getInstantiatorOf(Class<T> clazz) {
   if(clazz.isPrimitive()) {
      throw new IllegalArgumentException("Primitive types can't be instantiated in Java");
   }
   if(cache == null) {
      return strategy.newInstantiatorOf(clazz);
   }
   ObjectInstantiator<?> instantiator = cache.get(clazz.getName());
   if(instantiator == null) {
      ObjectInstantiator<?> newInstantiator = strategy.newInstantiatorOf(clazz);
      instantiator = cache.putIfAbsent(clazz.getName(), newInstantiator);
      if(instantiator == null) {
         instantiator = newInstantiator;
      }
   }
   return (ObjectInstantiator<T>) instantiator;
}
 
Example #5
Source File: SingleInstantiatorStrategy.java    From objenesis with Apache License 2.0 5 votes vote down vote up
/**
 * Create a strategy that will return always the same instantiator type. We assume this instantiator
 * has one constructor taking the class to instantiate in parameter.
 *
 * @param <T> the type we want to instantiate
 * @param instantiator the instantiator type
 */
public <T extends ObjectInstantiator<?>> SingleInstantiatorStrategy(Class<T> instantiator) {
   try {
      constructor = instantiator.getConstructor(Class.class);
   }
   catch(NoSuchMethodException e) {
      throw new ObjenesisException(e);
   }
}
 
Example #6
Source File: SingleInstantiatorStrategy.java    From objenesis with Apache License 2.0 5 votes vote down vote up
/**
 * Return an instantiator for the wanted type and of the one and only type of instantiator returned by this
 * class.
 *
 * @param <T> the type we want to instantiate
 * @param type Class to instantiate
 * @return The ObjectInstantiator for the class
 */
@SuppressWarnings("unchecked")
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
   try {
      return (ObjectInstantiator<T>) constructor.newInstance(type);
   } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
      throw new ObjenesisException(e);
   }
}
 
Example #7
Source File: SerializingInstantiatorStrategy.java    From objenesis with Apache License 2.0 5 votes vote down vote up
/**
 * Return an {@link ObjectInstantiator} allowing to create instance following the java
 * serialization framework specifications.
 *
 * @param type Class to instantiate
 * @return The ObjectInstantiator for the class
 */
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
   if(!Serializable.class.isAssignableFrom(type)) {
      throw new ObjenesisException(new NotSerializableException(type+" not serializable"));
   }
   if(JVM_NAME.startsWith(HOTSPOT) || PlatformDescription.isThisJVM(OPENJDK)) {
      // Java 7 GAE was under a security manager so we use a degraded system
      if(isGoogleAppEngine() && PlatformDescription.SPECIFICATION_VERSION.equals("1.7")) {
         return new ObjectInputStreamInstantiator<>(type);
      }
      return new SunReflectionFactorySerializationInstantiator<>(type);
   }
   else if(JVM_NAME.startsWith(DALVIK)) {
      if(PlatformDescription.isAndroidOpenJDK()) {
         return new ObjectStreamClassInstantiator<>(type);
      }
      return new AndroidSerializationInstantiator<>(type);
   }
   else if(JVM_NAME.startsWith(GNU)) {
      return new GCJSerializationInstantiator<>(type);
   }
   else if(JVM_NAME.startsWith(PERC)) {
      return new PercSerializationInstantiator<>(type);
   }

   return new SunReflectionFactorySerializationInstantiator<>(type);
}
 
Example #8
Source File: ObjenesisTest.java    From objenesis with Apache License 2.0 5 votes vote down vote up
@Test
public final void testGetInstantiatorOf() {
   Objenesis o = new ObjenesisStd();
   ObjectInstantiator<?> i1 = o.getInstantiatorOf(getClass());
   // Test instance creation
   assertEquals(getClass(), i1.newInstance().getClass());

   // Test caching
   ObjectInstantiator<?> i2 = o.getInstantiatorOf(getClass());
   assertSame(i1, i2);
}
 
Example #9
Source File: MagicInstantiatorTest.java    From objenesis with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewInstance() {
   ObjectInstantiator<EmptyClass> o1 = new MagicInstantiator<>(EmptyClass.class);
   assertEquals(EmptyClass.class, o1.newInstance().getClass());

   ObjectInstantiator<EmptyClass> o2 = new MagicInstantiator<>(EmptyClass.class);
   assertEquals(EmptyClass.class, o2.newInstance().getClass());
}
 
Example #10
Source File: Deserializer.java    From buck with Apache License 2.0 5 votes vote down vote up
public <T extends AddsToRuleKey> T create(Class<T> requestedClass) throws IOException {
  String className = stream.readUTF();
  Class<?> instanceClass;
  try {
    instanceClass = classFinder.find(className);
  } catch (ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
  Preconditions.checkState(requestedClass.isAssignableFrom(instanceClass));

  Optional<CustomClassBehaviorTag> serializerTag =
      CustomBehaviorUtils.getBehavior(instanceClass, CustomClassSerialization.class);
  if (serializerTag.isPresent()) {
    @SuppressWarnings("unchecked")
    CustomClassSerialization<T> customSerializer =
        (CustomClassSerialization<T>) serializerTag.get();
    return customSerializer.deserialize(this);
  }

  ObjectInstantiator instantiator =
      instantiators.computeIfAbsent(instanceClass, objenesis::getInstantiatorOf);
  @SuppressWarnings("unchecked")
  T instance = (T) instantiator.newInstance();
  ClassInfo<? super T> classInfo = DefaultClassInfoFactory.forInstance(instance);

  initialize(instance, classInfo);

  return instance;
}
 
Example #11
Source File: UnsafeInstantiatorStrategy.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * Return an {@link ObjectInstantiator} allowing to create instance without any constructor
 * being called.
 * @param type Class to instantiate
 * @return The ObjectInstantiator for the class
 */
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {

	if (FeatureDetection.hasUnsafe()) {
		return new UnsafeFactoryInstantiator<T>(type);
	}
	return super.newInstantiatorOf(type);
}
 
Example #12
Source File: GATKRegistrator.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Make sure that all FuncotationMap (which incl. all Funcotation concrete classes and members) classes are registered
 *  to support {@link org.broadinstitute.hellbender.tools.funcotator.FuncotationMap#create(FuncotationMap)}
 *
 * @param kryo Kryo instance to update in-place.  Never {@code null}
 */
@VisibleForTesting
public static void registerFuncotationMapDependencies(final Kryo kryo) {
    Utils.nonNull(kryo);
    Registration registration = kryo.register(TableFuncotation.class);
    registration.setInstantiator(new ObjectInstantiator<TableFuncotation>() {
        public TableFuncotation newInstance() {
            return TableFuncotation.create(new LinkedHashMap<>(), Allele.UNSPECIFIED_ALTERNATE_ALLELE, "TEMP", null);
        }
    });
    registration = kryo.register(VcfFuncotationMetadata.class);
    registration.setInstantiator(new ObjectInstantiator<VcfFuncotationMetadata>() {
        public VcfFuncotationMetadata newInstance() {
            return VcfFuncotationMetadata.create(new ArrayList<>());
        }
    });
    registration = kryo.register(VCFInfoHeaderLine.class);
    registration.setInstantiator(new ObjectInstantiator<VCFInfoHeaderLine>() {
        public VCFInfoHeaderLine newInstance() {
            return new VCFInfoHeaderLine("TMP", 2, VCFHeaderLineType.String, "");
        }
    });
    registration = kryo.register(Allele.class);
    registration.setInstantiator(new ObjectInstantiator<Allele>() {
        public Allele newInstance() {
            return Allele.create("TCGA");
        }
    });
}
 
Example #13
Source File: PreAnalyzeFieldsTest.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void throwAway() {
  log.info("BEFORE_CLASS BEGINS");
  // this is just ot keep checkClusterConfiguration happy... actually better to do this per-test
  // to avoid cross talk between tests (see SOLR-12801 test revamp in solr)
  // future versions of solr won't require this....
  Objenesis objenesis = new ObjenesisStd();
  ObjectInstantiator<MiniSolrCloudCluster> instantiatorOf = objenesis.getInstantiatorOf(MiniSolrCloudCluster.class);
  cluster = instantiatorOf.newInstance();
  log.info("BEFORE_CLASS ENDSS");
}
 
Example #14
Source File: OperationInstantiator.java    From artemis-odb-orion with Apache License 2.0 5 votes vote down vote up
@Override
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
	if (Operation.class.isAssignableFrom(type)) {
		return instantiator(type);
	} else {
		return fallback.newInstantiatorOf(type);
	}
}
 
Example #15
Source File: TCKTest.java    From objenesis with Apache License 2.0 4 votes vote down vote up
public <T> ObjectInstantiator<T> getInstantiatorOf(Class<T> clazz) {
   return null;
}
 
Example #16
Source File: ProxyingInstantiatorTest.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testJavaLangInstance() {
   ObjectInstantiator<Object> inst = new ProxyingInstantiator<>(Object.class);
   Object c = inst.newInstance();
   assertEquals("org.objenesis.subclasses.java.lang.Object$$$Objenesis", c.getClass().getName());
}
 
Example #17
Source File: ProxyingInstantiatorTest.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewInstance() {
   ObjectInstantiator<EmptyClass> inst = new ProxyingInstantiator<>(EmptyClass.class);
   EmptyClass c = inst.newInstance();
   assertEquals("org.objenesis.EmptyClass$$$Objenesis", c.getClass().getName());
}
 
Example #18
Source File: MagicInstantiatorTest.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testInternalInstantiator() {
   ObjectInstantiator<EmptyClass> o1 = new MagicInstantiator<>(EmptyClass.class).getInstantiator();
   assertEquals(EmptyClass.class, o1.newInstance().getClass());
}
 
Example #19
Source File: TCKTest.java    From objenesis with Apache License 2.0 4 votes vote down vote up
public <T> ObjectInstantiator<T> getInstantiatorOf(Class<T> clazz) {
   return null;
}
 
Example #20
Source File: ObjenesisTest.java    From objenesis with Apache License 2.0 4 votes vote down vote up
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
   return null;
}
 
Example #21
Source File: NetworkRegisterer.java    From killingspree with MIT License 4 votes vote down vote up
static public void register (EndPoint endPoint) {
    Registration registration;
    Kryo kryo = endPoint.getKryo();
    registration = kryo.register(ConnectMessage.class);
    registration.setInstantiator(new ObjectInstantiator<ConnectMessage>() {
        @Override
        public ConnectMessage newInstance() {
            return MessageObjectPool.instance.connectMessagePool.obtain();
        }
    });
    
    registration = kryo.register(ControlsMessage.class);
    registration.setInstantiator(new 
            ObjectInstantiator<ControlsMessage>() {
        
        @Override
        public ControlsMessage newInstance() {
            return MessageObjectPool.instance.controlsMessagePool.obtain();
        }
        
    });
    
    registration = kryo.register(EntityState.class);
    registration.setInstantiator(new 
            ObjectInstantiator<EntityState>() {
        
        @Override
        public EntityState newInstance() {
            return MessageObjectPool.instance.entityStatePool.obtain();
        }
        
    });
    
    registration = kryo.register(GameStateMessage.class);
    registration.setInstantiator(new 
            ObjectInstantiator<GameStateMessage>() {
        
        @Override
        public GameStateMessage newInstance() {
            return MessageObjectPool.instance.gameStateMessagePool.obtain();
        }
        
    });
    
    registration = kryo.register(AudioMessage.class);
    registration.setInstantiator(new 
            ObjectInstantiator<AudioMessage>() {
        
        @Override
        public AudioMessage newInstance() {
            return MessageObjectPool.instance.audioMessagePool.obtain();
        }
        
    });
    
    kryo.register(PlayerNamesMessage.class);
    kryo.register(ClientDetailsMessage.class);
    kryo.register(ServerStatusMessage.class);
    kryo.register(ServerStatusMessage.Status.class);
    kryo.register(ArrayList.class);
    kryo.register(Vector2.class);
    kryo.register(String.class);
    kryo.register(HashMap.class);
}
 
Example #22
Source File: StdInstantiatorStrategy.java    From objenesis with Apache License 2.0 4 votes vote down vote up
/**
 * Return an {@link ObjectInstantiator} allowing to create instance without any constructor being
 * called.
 *
 * @param type Class to instantiate
 * @return The ObjectInstantiator for the class
 */
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {

   if(PlatformDescription.isThisJVM(HOTSPOT) || PlatformDescription.isThisJVM(OPENJDK)) {
      // Java 7 GAE was under a security manager so we use a degraded system
      if(PlatformDescription.isGoogleAppEngine() && PlatformDescription.SPECIFICATION_VERSION.equals("1.7")) {
         if(Serializable.class.isAssignableFrom(type)) {
            return new ObjectInputStreamInstantiator<>(type);
         }
         return new AccessibleInstantiator<>(type);
      }
      // The UnsafeFactoryInstantiator would also work. But according to benchmarks, it is 2.5
      // times slower. So I prefer to use this one
      return new SunReflectionFactoryInstantiator<>(type);
   }
   else if(PlatformDescription.isThisJVM(DALVIK)) {
      if(PlatformDescription.isAndroidOpenJDK()) {
         // Starting at Android N which is based on OpenJDK
         return new UnsafeFactoryInstantiator<>(type);
      }
      if(ANDROID_VERSION <= 10) {
         // Android 2.3 Gingerbread and lower
         return new Android10Instantiator<>(type);
      }
      if(ANDROID_VERSION <= 17) {
         // Android 3.0 Honeycomb to 4.2 Jelly Bean
         return new Android17Instantiator<>(type);
      }
      // Android 4.3 until Android N
      return new Android18Instantiator<>(type);
   }
   else if(PlatformDescription.isThisJVM(GNU)) {
      return new GCJInstantiator<>(type);
   }
   else if(PlatformDescription.isThisJVM(PERC)) {
      return new PercInstantiator<>(type);
   }

   // Fallback instantiator, should work with most modern JVM
   return new UnsafeFactoryInstantiator<>(type);

}
 
Example #23
Source File: ConcurrentGetInstantiator.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Benchmark
public ObjectInstantiator<?> uncachedStd(ThreadState state) {
   return uncachedStd.getInstantiatorOf(toInstantiate[state.index++ % COUNT]);
}
 
Example #24
Source File: ConcurrentGetInstantiator.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Benchmark
public ObjectInstantiator<?> cachedStd(ThreadState state) {
   return cachedStd.getInstantiatorOf(toInstantiate[state.index++ % COUNT]);
}
 
Example #25
Source File: ConcurrentGetInstantiator.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Benchmark
public ObjectInstantiator<?> custom(ThreadState state) {
   return custom.newInstantiatorOf(toInstantiate[state.index++ % COUNT]);
}
 
Example #26
Source File: ConcurrentGetInstantiator.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Benchmark
public ObjectInstantiator<?> single(ThreadState state) {
   return single.newInstantiatorOf(toInstantiate[state.index++ % COUNT]);
}
 
Example #27
Source File: ConcurrentGetInstantiator.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Benchmark
public ObjectInstantiator<?> std(ThreadState state) {
   return std.newInstantiatorOf(toInstantiate[state.index++ % COUNT]);
}
 
Example #28
Source File: ConcurrentGetInstantiator.java    From objenesis with Apache License 2.0 4 votes vote down vote up
@Override
public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
   return new SunReflectionFactoryInstantiator<>(type);
}
 
Example #29
Source File: InstantiatorStrategy.java    From objenesis with Apache License 2.0 2 votes vote down vote up
/**
 * Create a dedicated instantiator for the given class
 *
 * @param <T> Type to instantiate
 * @param type Class that will be instantiated
 * @return Dedicated instantiator
 */
<T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type);
 
Example #30
Source File: Objenesis.java    From objenesis with Apache License 2.0 2 votes vote down vote up
/**
 * Will pick the best instantiator for the provided class. If you need to create a lot of
 * instances from the same class, it is way more efficient to create them from the same
 * ObjectInstantiator than calling {@link #newInstance(Class)}.
 *
 * @param <T> Type to instantiate
 * @param clazz Class to instantiate
 * @return Instantiator dedicated to the class
 */
<T> ObjectInstantiator<T> getInstantiatorOf(Class<T> clazz);