All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jparams.object.builder.util.ObjectUtils Maven / Gradle / Ivy

package com.jparams.object.builder.util;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

/**
 * Object utils
 */
public final class ObjectUtils
{
    private static Unsafe unsafe;

    static
    {
        try
        {
            final Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        }
        catch (final Exception e)
        {
            unsafe = null;
        }
    }

    private ObjectUtils()
    {
    }

    @SuppressWarnings("unchecked")
    public static  T createInstance(final Class clazz)
    {
        if (unsafe == null)
        {
            throw new UnsupportedOperationException("Failed to create an instance without constructor injection");
        }

        try
        {
            return (T) unsafe.allocateInstance(clazz);
        }
        catch (final InstantiationException e)
        {
            throw new UnsupportedOperationException("Failed to create an instance without constructor injection", e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy