| 1 | /* |
| 2 | * This file is part of JON. |
| 3 | * |
| 4 | * JON is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Lesser General Public License as published by |
| 6 | * the Free Software Foundation; either version 3 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * JON is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Lesser General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Lesser General Public License |
| 15 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | * |
| 17 | * Copyright 2007 Michael Doberenz |
| 18 | */ |
| 19 | package org.fuwjax.jon.type; |
| 20 | |
| 21 | import java.lang.reflect.Field; |
| 22 | |
| 23 | import org.fuwjax.jon.ObjectAccessException; |
| 24 | |
| 25 | /** |
| 26 | * DIRTY POOL: creates a new object using the Unsafe class. |
| 27 | * @author michaeldoberenz |
| 28 | */ |
| 29 | public final class UnsafeInstantiator{ |
| 30 | private static final String UNSAFE_FIELD = "theUnsafe"; //$NON-NLS-1$ |
| 31 | private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
| 32 | |
| 33 | private UnsafeInstantiator(){ |
| 34 | // utility class |
| 35 | } |
| 36 | |
| 37 | private static sun.misc.Unsafe getUnsafe(){ |
| 38 | try{ |
| 39 | return sun.misc.Unsafe.getUnsafe(); |
| 40 | }catch(RuntimeException e){ |
| 41 | try{ |
| 42 | final Field field = sun.misc.Unsafe.class.getDeclaredField(UNSAFE_FIELD); |
| 43 | field.setAccessible(true); |
| 44 | return (sun.misc.Unsafe)field.get(null); |
| 45 | }catch(Exception ex){ |
| 46 | throw new RuntimeException(ex); |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * DIRTY POOL: creates using the unsafe object. |
| 53 | * @param type the class to create |
| 54 | * @return the newly created instance |
| 55 | * @throws ObjectAccessException if an object relationship cannot be restored |
| 56 | */ |
| 57 | public static Object create(final Class<?> type) throws ObjectAccessException{ |
| 58 | try{ |
| 59 | return UNSAFE.allocateInstance(type); |
| 60 | }catch(InstantiationException e){ |
| 61 | throw ObjectAccessException.Message.ObjectNotAllocated.exception(e); |
| 62 | } |
| 63 | } |
| 64 | } |