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.eurekastreams.commons.reflection.ReflectiveInstantiator.java

/**
 * Instantiate an object of the input class type with the empty constructor.
 * Private constructors are handled.//from ww w  .j  av  a2  s.co m
 *
 * @param objType
 *            the type of class to instantiate.
 *
 * @return an object of the input class type.
 */
public Object instantiateObject(final Class<?> objType) {
    Constructor<?> emptyConstructor = null;
    for (Constructor<?> constructor : objType.getDeclaredConstructors()) {
        if (constructor.getParameterTypes().length == 0) {
            emptyConstructor = constructor;
            break;
        }
    }
    if (emptyConstructor == null) {
        String message = "Cannot find empty constructor for " + objType.getName();
        log.error(message);
        throw new RuntimeException(message);
    }

    // set it accessible, just in case
    emptyConstructor.setAccessible(true);

    Object obj = null;
    try {
        obj = emptyConstructor.newInstance(new Object[0]);
    } catch (Exception e) {
        String message = "Couldn't instantiate: " + objType.getName();
        log.error(message, e);
        throw new RuntimeException(message);
    }

    return obj;
}

From source file:org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtilTest.java

private void setMockedLog(boolean isDebugEnabled) throws Exception {

    Constructor<EndpointUtil> constructor = EndpointUtil.class.getDeclaredConstructor(new Class[0]);
    constructor.setAccessible(true);
    Object claimUtilObject = constructor.newInstance(new Object[0]);
    Field logField = claimUtilObject.getClass().getDeclaredField("log");

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);// www. j  ava 2s.co  m
    modifiersField.setInt(logField, logField.getModifiers() & ~Modifier.FINAL);

    logField.setAccessible(true);
    logField.set(claimUtilObject, mockedLog);
    when(mockedLog.isDebugEnabled()).thenReturn(isDebugEnabled);
}

From source file:com.cloud.agent.AgentShell.java

private void launchAgentFromClassInfo(String resourceClassNames) throws ConfigurationException {
    String[] names = resourceClassNames.split("\\|");
    for (String name : names) {
        Class<?> impl;//w w w.  j  a va2 s.  co m
        try {
            impl = Class.forName(name);
            final Constructor<?> constructor = impl.getDeclaredConstructor();
            constructor.setAccessible(true);
            ServerResource resource = (ServerResource) constructor.newInstance();
            launchAgent(getNextAgentId(), resource);
        } catch (final ClassNotFoundException e) {
            throw new ConfigurationException("Resource class not found: " + name + " due to: " + e.toString());
        } catch (final SecurityException e) {
            throw new ConfigurationException(
                    "Security excetion when loading resource: " + name + " due to: " + e.toString());
        } catch (final NoSuchMethodException e) {
            throw new ConfigurationException(
                    "Method not found excetion when loading resource: " + name + " due to: " + e.toString());
        } catch (final IllegalArgumentException e) {
            throw new ConfigurationException(
                    "Illegal argument excetion when loading resource: " + name + " due to: " + e.toString());
        } catch (final InstantiationException e) {
            throw new ConfigurationException(
                    "Instantiation excetion when loading resource: " + name + " due to: " + e.toString());
        } catch (final IllegalAccessException e) {
            throw new ConfigurationException(
                    "Illegal access exception when loading resource: " + name + " due to: " + e.toString());
        } catch (final InvocationTargetException e) {
            throw new ConfigurationException(
                    "Invocation target exception when loading resource: " + name + " due to: " + e.toString());
        }
    }
}

From source file:org.apache.hadoop.yarn.factories.impl.pb.RpcClientFactoryPBImpl.java

public Object getClient(Class<?> protocol, long clientVersion, InetSocketAddress addr, Configuration conf) {

    Constructor<?> constructor = cache.get(protocol);
    if (constructor == null) {
        Class<?> pbClazz = null;
        try {//from w  w  w  .  j av  a2 s . c om
            pbClazz = localConf.getClassByName(getPBImplClassName(protocol));
        } catch (ClassNotFoundException e) {
            throw new YarnRuntimeException("Failed to load class: [" + getPBImplClassName(protocol) + "]", e);
        }
        try {
            constructor = pbClazz.getConstructor(Long.TYPE, InetSocketAddress.class, Configuration.class);
            constructor.setAccessible(true);
            cache.putIfAbsent(protocol, constructor);
        } catch (NoSuchMethodException e) {
            throw new YarnRuntimeException("Could not find constructor with params: " + Long.TYPE + ", "
                    + InetSocketAddress.class + ", " + Configuration.class, e);
        }
    }
    try {
        Object retObject = constructor.newInstance(clientVersion, addr, conf);
        return retObject;
    } catch (InvocationTargetException e) {
        throw new YarnRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new YarnRuntimeException(e);
    } catch (InstantiationException e) {
        throw new YarnRuntimeException(e);
    }
}

From source file:org.springframework.boot.web.client.RestTemplateBuilder.java

private ClientHttpRequestFactory createRequestFactory(
        Class<? extends ClientHttpRequestFactory> requestFactory) {
    try {/*ww w  .  java 2  s.co  m*/
        Constructor<?> constructor = requestFactory.getDeclaredConstructor();
        constructor.setAccessible(true);
        return (ClientHttpRequestFactory) constructor.newInstance();
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:com.github.larsq.spring.embeddedamqp.SimpleAmqpMessageContainer.java

/**
 * Support method.//from   ww w .jav  a2 s.co  m
 *
 * @param clz
 * @return
 */
private Object invokeInnerClassConstructor(Class<?> clz) {
    try {
        Constructor<?> noArgConstructor = clz.getDeclaredConstructor(SimpleAmqpMessageContainer.class);
        if (!noArgConstructor.isAccessible()) {
            noArgConstructor.setAccessible(true);
        }

        return noArgConstructor.newInstance(this);
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
            | InvocationTargetException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.powertac.logtool.common.DomainObjectReader.java

private Object restoreInstance(Class<?> clazz, String[] args) throws MissingDomainObject {
    Domain domain = clazz.getAnnotation(Domain.class);
    if (domain instanceof Domain) {
        // only do this for @Domain classes
        Object thing = null;// w  ww.j a va 2s  .  c  om
        try {
            Constructor<?> cons = clazz.getDeclaredConstructor();
            cons.setAccessible(true);
            thing = cons.newInstance();
        } catch (Exception e) {
            log.warn("No default constructor for " + clazz.getName() + ": " + e.toString());
            return null;
        }
        String[] fieldNames = domain.fields();
        Field[] fields = new Field[fieldNames.length];
        Class<?>[] types = new Class<?>[fieldNames.length];
        for (int i = 0; i < fieldNames.length; i++) {
            fields[i] = ReflectionUtils.findField(clazz, resolveDoubleCaps(fieldNames[i]));
            if (null == fields[i]) {
                log.warn("No field in " + clazz.getName() + " named " + fieldNames[i]);
                types[i] = null;
            } else {
                types[i] = fields[i].getType();
            }
        }
        Object[] data = resolveArgs(types, args);
        if (null == data) {
            log.error("Could not resolve args for " + clazz.getName());
            return null;
        } else {
            for (int i = 0; i < fields.length; i++) {
                if (null == fields[i])
                    continue;
                fields[i].setAccessible(true);
                try {
                    fields[i].set(thing, data[i]);
                } catch (Exception e) {
                    log.error("Exception setting field: " + e.toString());
                    return null;
                }
            }
        }
        return thing;
    }
    return null;
}

From source file:com.iorga.webappwatcher.EventLogManager.java

public <E extends EventLog> E addEventLog(final Class<E> eventLogClass) {
    final E eventLog;
    synchronized (eventLogsQueueLock) {
        try {/*from   w  w  w. j ava2  s  . c  o  m*/
            final Constructor<E> constructor = eventLogClass.getDeclaredConstructor();
            constructor.setAccessible(true);
            eventLog = constructor.newInstance();
        } catch (final Exception e) {
            throw new IllegalArgumentException("Can't create a new " + eventLogClass.getName(), e);
        }

        eventLogsQueue.addLast(eventLog);

        eventLogsQueueCleaner.start(); // start the cleaner to check the potentially too old eventLogs to remove
    }
    return eventLog;
}

From source file:org.leo.benchmark.Benchmark.java

/**
 * @param collectionClass/*ww  w .  j av a 2s .  c  o m*/
 * @throws NoSuchMethodException
 * @throws SecurityException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void runMemoryBench(List<Class<? extends Collection>> collectionClasses) {
    for (Class<? extends Collection> clazz : collectionClasses) {
        try {
            // run some gc
            heavyGc();
            long usedMemory = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
            Constructor<? extends Collection> constructor = clazz.getDeclaredConstructor((Class<?>[]) null);
            constructor.setAccessible(true);
            // do the test on 100 objects, to be more accurate
            for (int i = 0; i < 100; i++) {
                this.collection = (Collection<String>) constructor.newInstance();
                // polulate
                collection.addAll(defaultCtx);
                warmUp();
            }
            // measure size
            long objectSize = (long) ((ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()
                    - usedMemory) / 100f);
            System.out.println(clazz.getCanonicalName() + " Object size : " + objectSize + " bytes");
            memoryResults.put((Class<? extends Collection<?>>) clazz, objectSize);
            collection.clear();
            collection = null;
        } catch (Exception e) {
            System.err.println("Failed running benchmark on class " + clazz.getCanonicalName());
            e.printStackTrace();
        }
    }
}

From source file:com.google.feedserver.util.BeanUtil.java

public Object createBeanInstance(Class<?> objectClass) {
    Constructor<?> c;
    try {/*  w  w  w .ja va  2s. c  o m*/
        c = objectClass.getConstructor();
    } catch (SecurityException e) {
        return null;
    } catch (NoSuchMethodException e) {
        if (objectClass == Timestamp.class) {
            return new Timestamp(System.currentTimeMillis());
        } else {
            return null;
        }
    }
    c.setAccessible(true);
    try {
        return c.newInstance();
    } catch (IllegalArgumentException e) {
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }
    return null;
}