1 /** 2 * Copyright 2006-2013 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package org.objenesis; 17 18 import java.io.Serializable; 19 20 import org.objenesis.instantiator.ObjectInstantiator; 21 22 /** 23 * Use Objenesis in a static way. <strong>It is strongly not recommended to use this class.</strong> 24 * 25 * @author Henri Tremblay 26 */ 27 public final class ObjenesisHelper { 28 29 private static final Objenesis OBJENESIS_STD = new ObjenesisStd(); 30 31 private static final Objenesis OBJENESIS_SERIALIZER = new ObjenesisSerializer(); 32 33 private ObjenesisHelper() { 34 } 35 36 /** 37 * Will create a new object without any constructor being called 38 * 39 * @param clazz Class to instantiate 40 * @return New instance of clazz 41 */ 42 public static Object newInstance(Class clazz) { 43 return OBJENESIS_STD.newInstance(clazz); 44 } 45 46 /** 47 * Will create an object just like it's done by ObjectInputStream.readObject (the default 48 * constructor of the first non serializable class will be called) 49 * 50 * @param clazz Class to instantiate 51 * @return New instance of clazz 52 */ 53 public static Serializable newSerializableInstance(Class clazz) { 54 return (Serializable) OBJENESIS_SERIALIZER.newInstance(clazz); 55 } 56 57 /** 58 * Will pick the best instantiator for the provided class. If you need to create a lot of 59 * instances from the same class, it is way more efficient to create them from the same 60 * ObjectInstantiator than calling {@link #newInstance(Class)}. 61 * 62 * @param clazz Class to instantiate 63 * @return Instantiator dedicated to the class 64 */ 65 public static ObjectInstantiator getInstantiatorOf(Class clazz) { 66 return OBJENESIS_STD.getInstantiatorOf(clazz); 67 } 68 69 /** 70 * Same as {@link #getInstantiatorOf(Class)} but providing an instantiator emulating 71 * ObjectInputStream.readObject behavior. 72 * 73 * @see #newSerializableInstance(Class) 74 * @param clazz Class to instantiate 75 * @return Instantiator dedicated to the class 76 */ 77 public static ObjectInstantiator getSerializableObjectInstantiatorOf(Class clazz) { 78 return OBJENESIS_SERIALIZER.getInstantiatorOf(clazz); 79 } 80 } 81