Example usage for java.lang.reflect Constructor setAccessible

List of usage examples for java.lang.reflect Constructor setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Constructor setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Document

A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.

Usage

From source file:org.rhq.enterprise.server.safeinvoker.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*from  w  ww . j  av a 2s. c om*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*from w  ww . jav  a  2s . c o  m*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("com.ppp")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:ch.flashcard.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*from   ww  w .  j a  va2s  . co m*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (replacement != null && !replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The <code>setAccessible(true)</code> method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).// ww w.j ava2 s  .  c om
 * 
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(final Constructor<?> ctor) {
    if (!Modifier.isPublic(ctor.getModifiers())
            || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
        ctor.setAccessible(true);
    }
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

/**
 * Get the handler instance.  //from  w  w w  .  j  ava2 s  .  com
 *  @param entigrator entigrator instance
 *  @param extension$ extension key
 *  @param handlerClass$ class name
 * @return handler instance.
 */

public static Object loadHandlerInstance(Entigrator entigrator, String extension$, String handlerClass$) {
    try {
        System.out.println(
                "ExtensionHandler:loadHandlerInstance:extension=" + extension$ + " handler=" + handlerClass$);

        Object obj = null;
        Class<?> cls = entigrator.getClass(handlerClass$);
        if (cls == null) {
            System.out.println("ExtensionHandler:loadHandlerInstance:1");
            Sack extension = entigrator.getEntityAtKey(extension$);
            String lib$ = extension.getElementItemAt("field", "lib");
            String jar$ = "jar:file:" + entigrator.getEntihome() + "/" + extension$ + "/" + lib$ + "!/";
            ArrayList<URL> urll = new ArrayList<URL>();
            urll.add(new URL(jar$));

            String[] sa = extension.elementListNoSorted("external");
            if (sa != null) {
                File file;
                for (String s : sa) {
                    file = new File(entigrator.getEntihome() + "/" + extension$ + "/" + s);
                    if (file.exists())
                        urll.add(new URL("jar:file:" + file.getPath() + "!/"));
                }
            }
            URL[] urls = urll.toArray(new URL[0]);
            URLClassLoader cl = URLClassLoader.newInstance(urls);

            //   Class<?>cls=entigrator.getClass(handlerClass$);

            cls = cl.loadClass(handlerClass$);

            if (cls == null) {
                System.out.println("ExtensionHandler:loadHandlerInstance:cannot load class =" + handlerClass$);
                return null;
            } else {
                //   System.out.println("ExtensionHandler:loadHandlerInstance:found class ="+handlerClass$);
                entigrator.putClass(handlerClass$, cls);
            }

        }

        try {

            Constructor[] ctors = cls.getDeclaredConstructors();
            System.out.println("ExtensionHandler:loadHandlerInstance:ctors=" + ctors.length);
            Constructor ctor = null;
            for (int i = 0; i < ctors.length; i++) {
                ctor = ctors[i];
                if (ctor.getGenericParameterTypes().length == 0)
                    break;
            }
            ctor.setAccessible(true);
            obj = ctor.newInstance();

        } catch (java.lang.NoClassDefFoundError ee) {
            System.out.println("ExtensionHandler:loadHandlerInstance:" + ee.toString());
            return null;
        }
        //if(obj!=null)
        System.out.println("ExtensionHandler:loadHandlerInstance:obj=" + obj.getClass().getName());
        return obj;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:org.bremersee.common.exception.ExceptionRegistry.java

private static Throwable findThrowableByDefaultConstructor(final Class<? extends Throwable> clazz,
        final String message, final Throwable cause) {
    try {//w  w  w . j  a  v a 2 s . com
        Constructor<? extends Throwable> constructor = clazz.getDeclaredConstructor();
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        Throwable t = constructor.newInstance();
        putMessage(t, message);
        if (cause != null) {
            t.initCause(cause); // NOSONAR
        }
        return t;

    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException // NOSONAR
            | InvocationTargetException e) { // NOSONAR
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finding throwable by default constructor failed. Class [" + clazz.getName()
                    + "] has no such constructor: " + e.getMessage() + " (" + e.getClass().getName() + ").");
        }
        return null;
    }
}

From source file:org.bremersee.common.exception.ExceptionRegistry.java

private static Throwable findThrowableByMessage(final Class<? extends Throwable> clazz, final String message,
        final Throwable cause) {
    try {// w ww  . java  2  s  .c  om
        Constructor<? extends Throwable> constructor = clazz.getDeclaredConstructor(String.class);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        Throwable t = constructor.newInstance(message);
        if (cause != null) {
            t.initCause(cause);
        }
        return t;

    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException // NOSONAR
            | InvocationTargetException e) { // NOSONAR
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finding throwable by message failed. Class [" + clazz.getName()
                    + "] has no suitable constructor: " + e.getMessage() + " (" + e.getClass().getName()
                    + ").");
        }
        return null;
    }
}

From source file:org.bremersee.common.exception.ExceptionRegistry.java

private static Throwable findThrowableByCause(final Class<? extends Throwable> clazz, final String message,
        final Throwable cause) {
    try {//from w  w  w  .j av a2  s.  co m
        Constructor<? extends Throwable> constructor = clazz.getDeclaredConstructor(Throwable.class);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        Throwable t = constructor.newInstance(cause);
        putMessage(t, message);
        return t;

    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException // NOSONAR
            | InvocationTargetException e) { // NOSONAR
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finding throwable by cause failed. Class [" + clazz.getName()
                    + "] has no suitable constructor: " + e.getMessage() + " (" + e.getClass().getName()
                    + ").");
        }
        return null;
    }
}

From source file:org.projectforge.common.BeanHelper.java

public static Object newInstance(final Class<?> clazz, final Class<?>[] paramTypes, final Object... params) {
    Constructor<?> constructor = null;
    try {/*  w w  w  . j  a va2  s .c o m*/
        constructor = clazz.getDeclaredConstructor(paramTypes);
    } catch (final SecurityException ex) {
        logInstantiationException(ex, clazz);
    } catch (final NoSuchMethodException ex) {
        logInstantiationException(ex, clazz);
    }
    constructor.setAccessible(true);
    try {
        return constructor.newInstance(params);
    } catch (final IllegalArgumentException ex) {
        logInstantiationException(ex, clazz);
    } catch (final InstantiationException ex) {
        logInstantiationException(ex, clazz);
    } catch (final IllegalAccessException ex) {
        logInstantiationException(ex, clazz);
    } catch (final InvocationTargetException ex) {
        logInstantiationException(ex, clazz);
    }
    return null;
}

From source file:com.linkbubble.util.Util.java

/**
 * From http://stackoverflow.com/a/5261472/328679
 *///  w  w  w. j av a  2s.c  o m
public static String getDefaultUserAgentString(Context context) {
    if (Build.VERSION.SDK_INT >= 17) {
        return WebSettings.getDefaultUserAgent(context);
    }

    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(context, null);
            return settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        return Config.sIsTablet ? Constant.USER_AGENT_CHROME_TABLET : Constant.USER_AGENT_CHROME_PHONE;
    }
}