001/*
002 *  Copyright 2013 Chris Pheby
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.jadira.reflection.cloning.objenesis;
017
018import org.jadira.reflection.access.unsafe.UnsafeOperations;
019import org.objenesis.ObjenesisException;
020import org.objenesis.instantiator.ObjectInstantiator;
021
022/**
023 * Provides the Objenesis API an instantiator implementation that can use Unsafe. 
024 * You may use this class independently of the cloning framework.
025 */
026public class UnsafeFactoryInstantiator<T> implements ObjectInstantiator<T> {
027
028        private Class<T> type;
029
030        private static final UnsafeOperations UNSAFE_OPERATIONS = UnsafeOperations.getUnsafeOperations();
031
032        /**
033         * Creates a new instance for the given type
034         * @param type The type to be instantiated by this instance
035         */
036        public UnsafeFactoryInstantiator(Class<T> type) {
037                this.type = type;
038        }
039
040        @Override
041        public T newInstance() {
042                try {
043                        return UNSAFE_OPERATIONS.allocateInstance(type);
044                } catch (IllegalStateException e) {
045                        throw new ObjenesisException(e.getCause());
046                }
047        }
048}