Example usage for java.lang Class getEnclosingClass

List of usage examples for java.lang Class getEnclosingClass

Introduction

In this page you can find the example usage for java.lang Class getEnclosingClass.

Prototype

@CallerSensitive
public Class<?> getEnclosingClass() throws SecurityException 

Source Link

Document

Returns the immediately enclosing class of the underlying class.

Usage

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java

private boolean isDependingOnOtherClass(String current, String other) {
    try {//from  w  w  w . j  av a  2s  . co m
        Class<?> currentClass = Class.forName(current);
        Class<?> otherClass = Class.forName(other);

        if (otherClass.isAssignableFrom(currentClass))
            return true;

        if (currentClass.getEnclosingClass() != null)
            return isDependingOnOtherClass(currentClass.getEnclosingClass().getName(), other);

        return false;
    } catch (ClassNotFoundException e) {
        return false;
    }
}

From source file:org.springframework.core.GenericTypeResolver.java

/**
 * Build a mapping of {@link TypeVariable#getName TypeVariable names} to
 * {@link Class concrete classes} for the specified {@link Class}. Searches
 * all super types, enclosing types and interfaces.
 *//*w  w w .  jav a  2s  .c om*/
public static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
    Map<TypeVariable, Type> ref = typeVariableCache.get(clazz);
    Map<TypeVariable, Type> typeVariableMap = (ref != null ? ref : null);

    if (typeVariableMap == null) {
        typeVariableMap = new HashMap<TypeVariable, Type>();

        // interfaces
        extractTypeVariablesFromGenericInterfaces(clazz.getGenericInterfaces(), typeVariableMap);

        // super class
        Type genericType = clazz.getGenericSuperclass();
        Class type = clazz.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                populateTypeMapFromParameterizedType(pt, typeVariableMap);
            }
            extractTypeVariablesFromGenericInterfaces(type.getGenericInterfaces(), typeVariableMap);
            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }

        // enclosing class
        type = clazz;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                populateTypeMapFromParameterizedType(pt, typeVariableMap);
            }
            type = type.getEnclosingClass();
        }

        typeVariableCache.put(clazz, typeVariableMap);
    }

    return typeVariableMap;
}

From source file:org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter.java

protected void registerEndpoint(String beanName, Endpoint<?> endpoint) {
    @SuppressWarnings("rawtypes")
    Class<? extends Endpoint> type = endpoint.getClass();
    if (AnnotationUtils.findAnnotation(type, ManagedResource.class) != null) {
        // Already managed
        return;//w w w.j  a  v a 2  s .co m
    }
    if (type.isMemberClass()
            && AnnotationUtils.findAnnotation(type.getEnclosingClass(), ManagedResource.class) != null) {
        // Nested class with @ManagedResource in parent
        return;
    }
    try {
        registerBeanNameOrInstance(getEndpointMBean(beanName, endpoint), beanName);
    } catch (MBeanExportException ex) {
        logger.error("Could not register MBean for endpoint [" + beanName + "]", ex);
    }
}

From source file:org.hyperledger.fabric.sdk.Endpoint.java

private void addNettyBuilderProps(NettyChannelBuilder channelBuilder, Properties props)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    if (props == null) {
        return;// w w w.  j  ava2  s .co m
    }

    for (Map.Entry<?, ?> es : props.entrySet()) {
        Object methodprop = es.getKey();
        if (methodprop == null) {
            continue;
        }
        String methodprops = String.valueOf(methodprop);

        Matcher match = METHOD_PATTERN.matcher(methodprops);

        String methodName = null;

        if (match.matches() && match.groupCount() == 1) {
            methodName = match.group(1).trim();

        }
        if (null == methodName || "forAddress".equals(methodName) || "build".equals(methodName)) {

            continue;
        }

        Object parmsArrayO = es.getValue();
        Object[] parmsArray;
        if (!(parmsArrayO instanceof Object[])) {
            parmsArray = new Object[] { parmsArrayO };

        } else {
            parmsArray = (Object[]) parmsArrayO;
        }

        Class<?>[] classParms = new Class[parmsArray.length];
        int i = -1;
        for (Object oparm : parmsArray) {
            ++i;

            if (null == oparm) {
                classParms[i] = Object.class;
                continue;
            }

            Class<?> unwrapped = WRAPPERS_TO_PRIM.get(oparm.getClass());
            if (null != unwrapped) {
                classParms[i] = unwrapped;
            } else {

                Class<?> clz = oparm.getClass();

                Class<?> ecz = clz.getEnclosingClass();
                if (null != ecz && ecz.isEnum()) {
                    clz = ecz;
                }

                classParms[i] = clz;
            }
        }

        final Method method = channelBuilder.getClass().getMethod(methodName, classParms);

        method.invoke(channelBuilder, parmsArray);

        if (logger.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder(200);
            String sep = "";
            for (Object p : parmsArray) {
                sb.append(sep).append(p + "");
                sep = ", ";

            }
            logger.trace(format("Endpoint with url: %s set managed channel builder method %s (%s) ", url,
                    method, sb.toString()));

        }

    }

}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

private static Class<?> getTopLevelClass(Class<?> clazz) {
    while (clazz.isMemberClass()) {
        clazz = clazz.getEnclosingClass();
    }//from   w w  w .  j  a v a  2s  .  c  o m
    return clazz;
}

From source file:com.cloudbees.plugins.credentials.CredentialsStore.java

/**
 * Constructor that auto-detects the {@link CredentialsProvider} that this {@link CredentialsStore} is associated
 * with by examining the outer classes until an outer class that implements {@link CredentialsProvider} is found.
 *
 * @since 2.0/*from   w  w  w. j  av a2s  .co  m*/
 */
@SuppressWarnings("unchecked")
public CredentialsStore() {
    // now let's infer our provider, Jesse will not like this evil
    Class<?> clazz = getClass().getEnclosingClass();
    while (clazz != null && !CredentialsProvider.class.isAssignableFrom(clazz)) {
        clazz = clazz.getEnclosingClass();
    }
    if (clazz == null) {
        throw new AssertionError(getClass() + " doesn't have an outer class. "
                + "Use the constructor that takes the Class object explicitly.");
    }
    if (!CredentialsProvider.class.isAssignableFrom(clazz)) {
        throw new AssertionError(getClass() + " doesn't have an outer class implementing CredentialsProvider. "
                + "Use the constructor that takes the Class object explicitly");
    }
    providerClass = (Class<? extends CredentialsProvider>) clazz;
}

From source file:com.bfd.harpc.config.ServerConfig.java

/**
 * ??TProcessor//from w  ww .j  av a 2 s.c  o  m
 * <p>
 * 
 * @param rpcMonitor
 * @param serverNode
 * @return TProcessor
 */
@SuppressWarnings("rawtypes")
protected TProcessor reflectProcessor(RpcMonitor rpcMonitor, ServerNode serverNode) {
    Class serviceClass = getRef().getClass();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Class<?>[] interfaces = serviceClass.getInterfaces();
    if (interfaces.length == 0) {
        throw new RpcException("Service class should implements Iface!");
    }

    // ??,load "Processor";
    TProcessor processor = null;
    for (Class clazz : interfaces) {
        String cname = clazz.getSimpleName();
        if (!cname.equals("Iface")) {
            continue;
        }
        String pname = clazz.getEnclosingClass().getName() + "$Processor";
        try {
            Class<?> pclass = classLoader.loadClass(pname);
            Constructor constructor = pclass.getConstructor(clazz);
            processor = (TProcessor) constructor
                    .newInstance(getProxy(classLoader, clazz, getRef(), rpcMonitor, serverNode));
        } catch (Exception e) {
            throw new RpcException("Refact error,please check your thift gen class!", e.getCause());
        }
    }

    if (processor == null) {
        throw new RpcException("Service class should implements $Iface!");
    }
    return processor;
}

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

@Inject
public void initCrons() {
    logger.info("Initialize cron jobs");
    try {//  www  .  ja v a 2s  . c  o m
        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);
    }
}

From source file:gridool.deployment.GridGetClassTask.java

protected ClassData execute() throws GridException {
    final Class<?> clazz;
    try {/*w w  w . j a va  2  s. c o m*/
        clazz = Class.forName(className, true, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException e) {
        String errmsg = "Class not found: " + className;
        LogFactory.getLog(getClass()).error(errmsg, e);
        throw new GridException(errmsg, e);
    }
    final byte[] b;
    try {
        b = ClassUtils.getClassAsBytes(clazz);
    } catch (IOException e) {
        String errmsg = "Failed serializing a class: " + clazz.getName();
        LogFactory.getLog(getClass()).error(errmsg, e);
        throw new GridException(errmsg, e);
    }
    final long timestamp = ClassUtils.getLastModified(clazz);

    final ClassData innerClassData = new ClassData(b, timestamp);
    ClassData classData = innerClassData;
    Class<?> enclosingClass = clazz.getEnclosingClass();
    while (enclosingClass != null) {
        classData = addEnclosingClass(classData, enclosingClass);
        enclosingClass = enclosingClass.getEnclosingClass();
    }
    return innerClassData;
}

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java

/**
 * Collects the list of required files without content.
 * @param clazz the class that related files should be collected for. (joda style)
 * @return List of files that are required for specified class or 
 * null if none are required. /*from  w w  w  .jav  a 2 s  .  com*/
 */
protected List<ClassLoaderFile> collectRequiredFiles(Class<?> clazz) {
    FileDependency fileDependency = clazz.getAnnotation(FileDependency.class);

    if (fileDependency == null)
        return null;

    List<ClassLoaderFile> files = new ArrayList<ClassLoaderFile>();

    if (fileDependency.dependencyProvider().equals(IFileDependencyProvider.class)) {// we have static files
        //         ContentType contentType = fileDependency.accessType() == FileAccess.ReadOnly ? 
        //                                    ContentType.ROFILE : ContentType.RWFILE;
        ContentType contentType = ContentType.ROFILE;

        String[] fileNames = fileDependency.files();

        if (fileNames == null || fileNames.length == 0)
            return null;

        for (String filename : fileNames) {
            File file = RemoteClassLoaderUtils.getRelativePathFile(filename);
            if (!file.exists()) {
                log.severe("Class " + clazz.getName() + " set file " + filename
                        + " as required, but the file is missing at " + file.getAbsolutePath());
                continue;
            }

            files.add(new ClassLoaderFile(filename, file.lastModified(), file.length(), contentType));
        }
    } else {// we have dynamic file list, let's process it.
        Class<? extends IFileDependencyProvider> dependentFilesProviderClass = fileDependency
                .dependencyProvider();
        if (dependentFilesProviderClass == null)
            return null;

        //checking if we can create this class
        if (dependentFilesProviderClass.isInterface()
                || Modifier.isAbstract(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is either abstract or interface.");

        if (dependentFilesProviderClass.getEnclosingClass() != null
                && !Modifier.isStatic(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is internal and not static. The class has to be static in this case.");

        Constructor<? extends IFileDependencyProvider> constructor = null;
        try {
            constructor = dependentFilesProviderClass.getDeclaredConstructor();
        } catch (NoSuchMethodException ex) {
            throw new JCloudScaleException(ex, "Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class cannot be created as it has no parameterless constructor.");
        }

        try {
            if (!constructor.isAccessible())
                constructor.setAccessible(true);

            IFileDependencyProvider provider = constructor.newInstance();

            for (DependentFile dependentFile : provider.getDependentFiles()) {
                File file = RemoteClassLoaderUtils.getRelativePathFile(dependentFile.filePath);
                if (!file.exists()) {
                    log.severe("Class " + clazz.getName() + " set file " + dependentFile.filePath
                            + " as required, but the file is missing.");
                    continue;
                }

                //               ContentType contentType = dependentFile.accessType == FileAccess.ReadOnly ? 
                //                     ContentType.ROFILE : ContentType.RWFILE;
                ContentType contentType = ContentType.ROFILE;

                files.add(new ClassLoaderFile(file.getPath(), file.lastModified(), file.length(), contentType));
            }
        } catch (Exception ex) {
            log.severe("Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                    + clazz.getName() + " threw exception during execution:" + ex.toString());
            throw new JCloudScaleException(ex,
                    "Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                            + clazz.getName() + " threw exception during execution.");
        }
    }

    return files;
}