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.apache.hadoop.yarn.factories.impl.pb.RpcServerFactoryPBImpl.java

@Override
public Server getServer(Class<?> protocol, Object instance, InetSocketAddress addr, Configuration conf,
        SecretManager<? extends TokenIdentifier> secretManager, int numHandlers, String portRangeConfig) {

    Constructor<?> constructor = serviceCache.get(protocol);
    if (constructor == null) {
        Class<?> pbServiceImplClazz = null;
        try {/*from  w w  w  .  ja  v a 2  s  .  c  om*/
            pbServiceImplClazz = localConf.getClassByName(getPbServiceImplClassName(protocol));
        } catch (ClassNotFoundException e) {
            throw new YarnRuntimeException(
                    "Failed to load class: [" + getPbServiceImplClassName(protocol) + "]", e);
        }
        try {
            constructor = pbServiceImplClazz.getConstructor(protocol);
            constructor.setAccessible(true);
            serviceCache.putIfAbsent(protocol, constructor);
        } catch (NoSuchMethodException e) {
            throw new YarnRuntimeException("Could not find constructor with params: " + Long.TYPE + ", "
                    + InetSocketAddress.class + ", " + Configuration.class, e);
        }
    }

    Object service = null;
    try {
        service = constructor.newInstance(instance);
    } catch (InvocationTargetException e) {
        throw new YarnRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new YarnRuntimeException(e);
    } catch (InstantiationException e) {
        throw new YarnRuntimeException(e);
    }

    Class<?> pbProtocol = service.getClass().getInterfaces()[0];
    Method method = protoCache.get(protocol);
    if (method == null) {
        Class<?> protoClazz = null;
        try {
            protoClazz = localConf.getClassByName(getProtoClassName(protocol));
        } catch (ClassNotFoundException e) {
            throw new YarnRuntimeException("Failed to load class: [" + getProtoClassName(protocol) + "]", e);
        }
        try {
            method = protoClazz.getMethod("newReflectiveBlockingService", pbProtocol.getInterfaces()[0]);
            method.setAccessible(true);
            protoCache.putIfAbsent(protocol, method);
        } catch (NoSuchMethodException e) {
            throw new YarnRuntimeException(e);
        }
    }

    try {
        return createServer(pbProtocol, addr, conf, secretManager, numHandlers,
                (BlockingService) method.invoke(null, service), portRangeConfig);
    } catch (InvocationTargetException e) {
        throw new YarnRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new YarnRuntimeException(e);
    } catch (IOException e) {
        throw new YarnRuntimeException(e);
    }
}

From source file:org.jgentleframework.utils.ReflectUtils.java

/**
 * Creates an object instance.//from   w w  w  .ja v  a 2  s .  c o  m
 * 
 * @param clazz
 *            the object class type
 * @param args
 *            the arguments of the constructor need to be use to instantiate
 *            bean. instance.
 * @return tr v? i tng Object va c khi to.
 */
@SuppressWarnings("unchecked")
public static <T> T createInstance(Class<T> clazz, Object... args) {

    T result = null;
    try {
        Constructor<T> constructor = null;
        if (args == null) {
            constructor = clazz.getDeclaredConstructor();
        } else {
            List<Class<?>> argsType = new ArrayList<Class<?>>();
            for (Object arg : args) {
                argsType.add(arg.getClass());
            }
            constructor = clazz.getDeclaredConstructor(argsType.toArray(new Class<?>[argsType.size()]));
        }
        constructor.setAccessible(true);
        result = args == null ? (T) constructor.newInstance() : constructor.newInstance(args);
    } catch (InstantiationException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (IllegalAccessException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (SecurityException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (NoSuchMethodException e) {
        if (args != null) {
            for (Constructor<?> cons : clazz.getDeclaredConstructors()) {
                cons.setAccessible(true);
                try {
                    result = (T) cons.newInstance(args);
                } catch (IllegalArgumentException e1) {
                    continue;
                } catch (InstantiationException e1) {
                    if (log.isFatalEnabled()) {
                        log.fatal("Could not create instance basing on target class ['" + clazz + "']", e1);
                    }
                } catch (IllegalAccessException e1) {
                    if (log.isFatalEnabled()) {
                        log.fatal("Could not create instance basing on target class ['" + clazz + "']", e1);
                    }
                } catch (InvocationTargetException e1) {
                    if (log.isFatalEnabled()) {
                        log.fatal("Could not create instance basing on target class ['" + clazz + "']", e1);
                    }
                }
            }
            if (result == null) {
                if (log.isFatalEnabled()) {
                    log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
                }
            }
        } else {
            if (log.isFatalEnabled()) {
                log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
            }
        }
    } catch (IllegalArgumentException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (InvocationTargetException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    }
    return result;
}

From source file:org.lilyproject.avro.AvroConverter.java

public RuntimeException convert(AvroGenericException avroException) {
    try {//  w  ww.  j  a  va 2 s  .c o  m
        // Attempt to restore the original exception: only for RuntimeExceptions which
        // have a constructor that takes a string argument.
        Class exceptionClass = Class.forName(avroException.getExceptionClass());
        if (RuntimeException.class.isAssignableFrom(exceptionClass)) {
            Constructor constructor = exceptionClass.getConstructor(String.class);
            constructor.setAccessible(true);
            RuntimeException runtimeException = (RuntimeException) constructor
                    .newInstance(avroException.getMessage$());
            restoreCauses(avroException.getRemoteCauses(), runtimeException);
            return runtimeException;
        }
    } catch (Exception e) {
        // cannot restore the original exception, will create a generic exception
    }

    RuntimeException exception = new RuntimeException(
            avroException.getExceptionClass() + ": " + avroException.getMessage());
    restoreCauses(avroException.getRemoteCauses(), exception);
    return exception;
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

public AbstractComponetAdapter getComponentAdapter(Acomponent ac) {
    for (Class in : ClassScan.findAll().assignableTo(AbstractComponetAdapter.class)
            .in("com.m4rc310.cb.builders.adapters")) {
        if (in == AbstractComponetAdapter.class) {
            continue;
        }/*from   w  ww .  j av a 2 s  .c  om*/

        try {
            Constructor constructor = in.getDeclaredConstructor();
            constructor.setAccessible(true);
            AbstractComponetAdapter adapter = (AbstractComponetAdapter) constructor.newInstance();
            if (adapter.isComponentFor(ac)) {
                return adapter;
            }
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException e) {
            infoError(e);
        }
    }

    throw new UnsupportedOperationException(
            "No h um <AbstractComponetAdapter> registrado para Acomponent: " + ac.ref());
}

From source file:org.nuxeo.ecm.platform.forms.layout.service.WebLayoutManagerImpl.java

@Override
public WidgetTypeHandler getWidgetTypeHandler(TagConfig config, String typeCategory, String typeName)
        throws WidgetException {
    if (StringUtils.isBlank(typeCategory)) {
        typeCategory = getDefaultStoreCategory();
    }/*from  w w  w  .  ja v a2  s .c o  m*/
    WidgetType type = getLayoutStore().getWidgetType(typeCategory, typeName);
    if (type == null) {
        return null;
    }
    WidgetTypeHandler handler;
    Class<?> klass = type.getWidgetTypeClass();
    if (klass == null) {
        // implicit handler is the "template" one
        handler = new TemplateWidgetTypeHandler(config);
    } else {
        try {
            Constructor<?> ctor = klass.getDeclaredConstructor(TagConfig.class);
            ctor.setAccessible(true);
            handler = (WidgetTypeHandler) ctor.newInstance(config);
        } catch (ReflectiveOperationException e) {
            log.error("Caught error when instanciating widget type handler", e);
            return null;
        }
    }
    handler.setProperties(type.getProperties());
    return handler;
}

From source file:com.centurylink.cloud.sdk.core.client.SdkClientBuilder.java

@Override
public ResteasyClient build() {
    ClientConfiguration config = new ClientConfiguration(getProviderFactory());
    for (Map.Entry<String, Object> entry : properties.entrySet()) {
        config.property(entry.getKey(), entry.getValue());
    }/* w w  w. ja  v  a  2s . co m*/

    ExecutorService executor = asyncExecutor;

    boolean cleanupExecutor = false;
    if (executor == null) {
        cleanupExecutor = true;
        executor = Executors.newFixedThreadPool(10);
    }

    ClientHttpEngine engine = httpEngine;
    if (engine == null) {
        engine = initDefaultEngine();
    }

    try {
        Constructor<ResteasyClient> constructor = ResteasyClient.class.getDeclaredConstructor(
                ClientHttpEngine.class, ExecutorService.class, boolean.class, ClientConfiguration.class);
        constructor.setAccessible(true);
        return constructor.newInstance(engine, executor, cleanupExecutor, config);
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
            | InvocationTargetException ex) {
        throw new ClcClientException(ex);
    }

}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private Object instantiate(Class<?> customSerializer, Class<?> instanceClass)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, SerializationException {
    if (customSerializer != null) {
        for (Method method : customSerializer.getMethods()) {
            if ("instantiate".equals(method.getName())) {
                return method.invoke(null, this);
            }//  ww w . jav a2s .co  m
        }
        // Ok to not have one.
    }

    if (instanceClass.isArray()) {
        int length = readInt();
        // We don't pre-allocate the array; this prevents an allocation attack
        return new BoundedList<Object>(instanceClass.getComponentType(), length);
    } else if (instanceClass.isEnum()) {
        Enum<?>[] enumConstants = (Enum[]) instanceClass.getEnumConstants();
        int ordinal = readInt();
        assert (ordinal >= 0 && ordinal < enumConstants.length);
        return enumConstants[ordinal];
    } else {
        Constructor<?> constructor = instanceClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();
    }
}

From source file:org.jenkins.tools.test.PluginCompatTester.java

private UpdateSite.Data newUpdateSiteData(UpdateSite us, JSONObject jsonO) throws RuntimeException {
    try {/* ww w . j  a v a 2s. com*/
        Constructor<UpdateSite.Data> dataConstructor = UpdateSite.Data.class
                .getDeclaredConstructor(UpdateSite.class, JSONObject.class);
        dataConstructor.setAccessible(true);
        return dataConstructor.newInstance(us, jsonO);
    } catch (Exception e) {
        throw new RuntimeException("UpdateSite.Data instanciation problems", e);
    }
}

From source file:org.talend.daikon.properties.PropertiesImpl.java

@Override
public NamedThing createPropertyInstance(NamedThing otherProp) throws ReflectiveOperationException {
    NamedThing thisProp = null;/*from  w w  w  .j a  v  a  2s .  co m*/
    Class<? extends NamedThing> otherClass = otherProp.getClass();
    if (Property.class.isAssignableFrom(otherClass)) {
        Property<?> otherPy = (Property<?>) otherProp;
        Constructor<? extends NamedThing> c = otherClass.getDeclaredConstructor(String.class, String.class);
        c.setAccessible(true);
        thisProp = c.newInstance(otherPy.getType(), otherPy.getName());
    } else if (Properties.class.isAssignableFrom(otherClass)) {
        // Look for single arg String, but an inner class will have a Properties as first arg
        Constructor<?>[] constructors = otherClass.getConstructors();
        for (Constructor<?> c : constructors) {
            Class<?> pts[] = c.getParameterTypes();
            c.setAccessible(true);
            if (pts.length == 1 && String.class.isAssignableFrom(pts[0])) {
                thisProp = (NamedThing) c.newInstance(otherProp.getName());
                break;
            }
            if (pts.length == 2 && Properties.class.isAssignableFrom(pts[0])
                    && String.class.isAssignableFrom(pts[1])) {
                thisProp = (NamedThing) c.newInstance(this, otherProp.getName());
                break;
            }
        }
        if (thisProp == null) {
            TalendRuntimeException.unexpectedException(
                    "Failed to find a proper constructor in Properties : " + otherClass.getName());
        }
    } else {
        TalendRuntimeException.unexpectedException(
                "Unexpected property class: " + otherProp.getClass() + " prop: " + otherProp);
    }
    return thisProp;
}

From source file:com.smartitengineering.generator.engine.service.impl.ReportConfigServiceImpl.java

@Inject
public void initCrons() {
    logger.info("Initialize cron jobs");
    try {/*from   w  ww.j  av  a 2  s .  c  om*/
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = new JobDetail("reportSyncJob", "reportSyncPoll", EventSyncJob.class);
        Trigger trigger = new DateIntervalTrigger("reportSyncTrigger", "reportSyncPoll",
                DateIntervalTrigger.IntervalUnit.MINUTE, 5);
        JobDetail redetail = new JobDetail("reportReSyncJob", "reportReSyncPoll", EventReSyncJob.class);
        Trigger retrigger = new DateIntervalTrigger("reportReSyncTrigger", "reportReSyncPoll",
                DateIntervalTrigger.IntervalUnit.DAY, 1);
        JobDetail reportDetail = new JobDetail("reportJob", "reportPoll", ReportJob.class);
        Trigger reportTrigger = new DateIntervalTrigger("reportTrigger", "reportPoll",
                DateIntervalTrigger.IntervalUnit.MINUTE, 1);
        scheduler.setJobFactory(new JobFactory() {

            public Job newJob(TriggerFiredBundle bundle) throws SchedulerException {
                try {
                    Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
                    if (ReportConfigServiceImpl.class.equals(jobClass.getEnclosingClass())) {
                        Constructor<? extends Job> constructor = (Constructor<? extends Job>) jobClass
                                .getDeclaredConstructors()[0];
                        constructor.setAccessible(true);
                        Job job = constructor.newInstance(ReportConfigServiceImpl.this);
                        return job;
                    } else {
                        return jobClass.newInstance();
                    }
                } catch (Exception ex) {
                    throw new SchedulerException(ex);
                }
            }
        });
        scheduler.start();
        scheduler.scheduleJob(detail, trigger);
        scheduler.scheduleJob(redetail, retrigger);
        scheduler.scheduleJob(reportDetail, reportTrigger);
    } catch (Exception ex) {
        logger.warn("Could initialize cron job!", ex);
    }
}