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.core.platform.FeatureDetection;
019import org.objenesis.instantiator.ObjectInstantiator;
020import org.objenesis.strategy.StdInstantiatorStrategy;
021
022/**
023 * Provides the Objenesis API a strategy for using sun.misc.Unsafe as a class construction
024 * technique. If unsafe is unavailable, delegates to the standard built in strategy.
025 * You may use this class independently of the cloning framework.
026 */
027public class UnsafeInstantiatorStrategy extends StdInstantiatorStrategy {
028        /**
029         * Return an {@link ObjectInstantiator} allowing to create instance without any constructor
030         * being called.
031         * @param type Class to instantiate
032         * @return The ObjectInstantiator for the class
033         */
034        public <T> ObjectInstantiator<T> newInstantiatorOf(Class<T> type) {
035
036                if (FeatureDetection.hasUnsafe()) {
037                        return new UnsafeFactoryInstantiator<T>(type);
038                }
039                return super.newInstantiatorOf(type);
040        }
041}