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:io.werval.runtime.util.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType) {
    Reference<Map<TypeVariable<?>, Type>> ref = CACHE.get(targetType);
    Map<TypeVariable<?>, Type> map = ref != null ? ref.get() : null;

    if (map == null) {
        map = new HashMap<>();

        // Populate interfaces
        buildTypeVariableMap(targetType.getGenericInterfaces(), map);

        // Populate super classes and interfaces
        Type genericType = targetType.getGenericSuperclass();
        Class<?> type = targetType.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType) {
                buildTypeVariableMap((ParameterizedType) genericType, map);
            }//from  www.j a va 2s.  com
            buildTypeVariableMap(type.getGenericInterfaces(), map);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }

        // Populate enclosing classes
        type = targetType;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType) {
                buildTypeVariableMap((ParameterizedType) genericType, map);
            }

            type = type.getEnclosingClass();
        }

        if (cacheEnabled) {
            CACHE.put(targetType, new WeakReference<>(map));
        }
    }

    return map;
}

From source file:com.kildeen.visor.core.api.permission.DefaultPermissionConverter.java

@Override
public String getPartId(final Class<? extends PartPermission> permissionClass) {
    String permission = WordUtils.uncapitalize(permissionClass.getEnclosingClass().getSimpleName())
            + permissionClass.getSimpleName();
    return permission;
}

From source file:adalid.core.XS1.java

static Object initialiseField(Object declaringObject, Field declaringField) {
    if (declaringObject == null || declaringField == null) {
        return null;
    }//from w  ww.  j  av a 2  s .  c o  m
    String declaringFieldName = declaringField.getName();
    Class<?> declaringFieldType = declaringField.getType();
    if (NamedValue.class.equals(declaringFieldType)) {
        return NamedValueCache.getInstance(declaringFieldName);
    }
    String fieldName = declaringFieldName;
    Class<?> fieldType = getFieldType(declaringFieldType);
    if (fieldType == null) {
        return null;
    }
    Object instance = null;
    Class<?> declaringClass = declaringObject.getClass();
    Class<?> enclosingClass = fieldType.getEnclosingClass();
    boolean memberClass = fieldType.isMemberClass();
    Entity declaringEntity = declaringObject instanceof Entity ? (Entity) declaringObject : null;
    Artifact declaringArtifact = declaringObject instanceof Artifact ? (Artifact) declaringObject : null;
    boolean declaringArtifactIsParameter = false;
    if (declaringObject instanceof DataArtifact) {
        DataArtifact declaringDataArtifact = (DataArtifact) declaringObject;
        declaringArtifactIsParameter = declaringDataArtifact.isParameter();
    }
    String errmsg = "failed to create a new instance of field " + declaringField + " at " + declaringObject;
    try {
        CastingField castingFieldAnnotation = getCastingFieldAnnotation(declaringField, fieldType);
        if (castingFieldAnnotation != null) {
            String name = castingFieldAnnotation.value();
            Field field = getFieldToBeCasted(true, fieldName, name, declaringClass, fieldType);
            if (field != null) {
                errmsg = "failed to set casting field " + declaringField + " at " + declaringObject;
                instance = field.get(declaringObject);
                //                  if (instance == null) {
                //                      logFieldErrorMessage(fieldName, name, declaringClass, field, "field " + name + " is not allocated");
                //                  }
            }
        } else if (memberClass && enclosingClass != null && enclosingClass.isAssignableFrom(declaringClass)) {
            if (Operation.class.isAssignableFrom(fieldType)) {
                if (declaringArtifact == null) {
                    instance = fieldType.getConstructor(enclosingClass).newInstance(declaringObject);
                } else if (declaringEntity == null) {
                    TLC.setDeclaringArtifact(declaringArtifact);
                    instance = fieldType.getConstructor(enclosingClass).newInstance(declaringObject);
                    TLC.removeDeclaringArtifact();
                } else {
                    String key = fieldType.getSimpleName();
                    Map<String, Class<?>> map = declaringEntity.getOperationClassesMap();
                    Class<?> fieldTypeX = map.containsKey(key) ? map.get(key) : fieldType;
                    Class<?> enclosingClassX = fieldTypeX.getEnclosingClass();
                    TLC.setDeclaringArtifact(declaringArtifact);
                    instance = fieldTypeX.getConstructor(enclosingClassX).newInstance(declaringObject);
                    TLC.removeDeclaringArtifact();
                }
            } else {
                instance = fieldType.getConstructor(enclosingClass).newInstance(declaringObject);
            }
        } else if (enclosingClass == null) {
            if (Entity.class.isAssignableFrom(fieldType)) {
                if (declaringArtifact == null) {
                    instance = fieldType.newInstance();
                } else {
                    //                      Method method = fieldType.getMethod(GET_INSTANCE, new Class<?>[]{Artifact.class});
                    //                      instance = method.invoke(null, declaringObject);
                    Class<?> type = getTrueType(fieldType);
                    checkAbstractClassReference(declaringField, type);
                    String path = declaringArtifact.getClassPath();
                    int depth = declaringArtifact.depth() + 1;
                    int round = round(type, declaringArtifact);
                    TLC.getProject().getParser().setMaxDepthReached(depth);
                    TLC.getProject().getParser().setMaxRoundReached(round);
                    FieldAllocationSettings settings = new FieldAllocationSettings(declaringField,
                            declaringObject, depth, round);
                    int maxDepth = settings.getMaxDepth();
                    int maxRound = settings.getMaxRound();
                    String method1 = "allocate(maxDepth={0}, maxRound={1})";
                    String method2 = MessageFormat.format(method1, maxDepth, maxRound);
                    String remark1 = "maxDepth<" + depth;
                    String remark2 = "maxRound<" + round;
                    String pattern;
                    String remarks;
                    if (declaringArtifactIsParameter || declaringArtifact.depth() == 0
                            || (depth <= maxDepth && round <= maxRound)) {
                        TLC.getProject().getParser().track(depth, round, path, type, fieldName, method2, null);
                        instance = type.getConstructor(Artifact.class, Field.class).newInstance(declaringObject,
                                declaringField);
                        TLC.getProject().getParser().increaseEntityCount();
                    } else {
                        pattern = "{1}, {0} not allocated";
                        if (depth > maxDepth) {
                            remarks = MessageFormat.format(pattern, fieldName, remark1);
                            TLC.getProject().getParser().alert(depth, round, path, type, fieldName, method2,
                                    remarks);
                        }
                        if (round > maxRound) {
                            remarks = MessageFormat.format(pattern, fieldName, remark2);
                            TLC.getProject().getParser().alert(depth, round, path, type, fieldName, method2,
                                    remarks);
                        }
                    }
                }
            } else {
                instance = fieldType.newInstance();
            }
        }
        if (instance instanceof AbstractArtifact) {
            // do not declare here; it will be declared at the corresponding finalise method
            AbstractArtifact abstractArtifact = (AbstractArtifact) instance;
            abstractArtifact.setName(fieldName);
            abstractArtifact.setDeclaringArtifact(declaringArtifact);
            abstractArtifact.setDeclaringField(declaringField);
            if (instance instanceof VariantX) {
                VariantX variantX = (VariantX) instance;
                variantX.setDataType(declaringFieldType);
            }
        }
    } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | NoSuchMethodException
            | InvocationTargetException ex) {
        throw new InstantiationRuntimeException(errmsg, ex);
    }
    return instance;
}

From source file:org.opensingular.form.processor.TypeProcessorAttributeReadFromFile.java

@Nonnull
private String concatNames(@Nonnull Class<?> context, @Nonnull String name) {
    return context.getEnclosingClass().getSimpleName() + '$' + name;
}

From source file:org.opensingular.form.processor.TypeProcessorAttributeReadFromFile.java

/** Verifica se h um arquivos com valores de atributos associados a classe informada. */
@Nullable//from   ww w . ja v  a  2 s. co  m
private URL lookForFile(@Nonnull Class<?> typeClass) {
    String name = typeClass.getSimpleName();
    Class<?> context = typeClass;
    for (; context.isMemberClass(); context = context.getEnclosingClass()) {
        name = concatNames(context, name);
    }
    return context.getResource(name + SUFFIX_PROPERTIES);
}

From source file:org.jtester.utility.ReflectionUtils.java

/**
 * Creates an instance of the given type
 * /*from w w  w .  ja  v  a 2  s. com*/
 * @param <T>
 *            The type of the instance
 * @param type
 *            The type of the instance
 * @param bypassAccessibility
 *            If true, no exception is thrown if the parameterless
 *            constructor is not public
 * @param argumentTypes
 *            The constructor arg types, not null
 * @param arguments
 *            The constructor args, not null
 * @return An instance of this type
 * @throws JTesterException
 *             If an instance could not be created
 */
@SuppressWarnings("rawtypes")
public static <T> T createInstanceOfType(Class<T> type, boolean bypassAccessibility, Class[] argumentTypes,
        Object[] arguments) {

    if (type.isMemberClass() && !isStatic(type.getModifiers())) {
        throw new JTesterException(
                "Creation of an instance of a non-static innerclass is not possible using reflection. The type "
                        + type.getSimpleName()
                        + " is only known in the context of an instance of the enclosing class "
                        + type.getEnclosingClass().getSimpleName()
                        + ". Declare the innerclass as static to make construction possible.");
    }
    try {
        Constructor<T> constructor = type.getDeclaredConstructor(argumentTypes);
        if (bypassAccessibility) {
            constructor.setAccessible(true);
        }
        return constructor.newInstance(arguments);

    } catch (InvocationTargetException e) {
        throw new JTesterException("Error while trying to create object of class " + type.getName(),
                e.getCause());

    } catch (Exception e) {
        throw new JTesterException("Error while trying to create object of class " + type.getName(), e);
    }
}

From source file:net.jodah.typetools.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType,
        Class<?> functionalInterface) {
    Reference<Map<TypeVariable<?>, Type>> ref = typeVariableCache.get(targetType);
    Map<TypeVariable<?>, Type> map = ref != null ? ref.get() : null;

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

        // Populate lambdas
        if (functionalInterface != null)
            populateLambdaArgs(functionalInterface, targetType, map);

        // Populate interfaces
        populateSuperTypeArgs(targetType.getGenericInterfaces(), map, functionalInterface != null);

        // Populate super classes and interfaces
        Type genericType = targetType.getGenericSuperclass();
        Class<?> type = targetType.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) genericType, map, false);
            populateSuperTypeArgs(type.getGenericInterfaces(), map, false);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }/*from   w w  w. j  av  a  2  s.  com*/

        // Populate enclosing classes
        type = targetType;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) genericType, map, functionalInterface != null);

            type = type.getEnclosingClass();
        }

        if (CACHE_ENABLED)
            typeVariableCache.put(targetType, new WeakReference<Map<TypeVariable<?>, Type>>(map));
    }

    return map;
}

From source file:org.unitils.util.ReflectionUtils.java

/**
 * Creates an instance of the given type
 * //from  w w  w  .ja  va2s. c om
 * @param <T>
 *            The type of the instance
 * @param type
 *            The type of the instance
 * @param bypassAccessibility
 *            If true, no exception is thrown if the parameterless
 *            constructor is not public
 * @param argumentTypes
 *            The constructor arg types, not null
 * @param arguments
 *            The constructor args, not null
 * @return An instance of this type
 * @throws UnitilsException
 *             If an instance could not be created
 */
public static <T> T createInstanceOfType(Class<T> type, boolean bypassAccessibility, Class[] argumentTypes,
        Object[] arguments) {

    if (type.isMemberClass() && !isStatic(type.getModifiers())) {
        throw new UnitilsException(
                "Creation of an instance of a non-static innerclass is not possible using reflection. The type "
                        + type.getSimpleName()
                        + " is only known in the context of an instance of the enclosing class "
                        + type.getEnclosingClass().getSimpleName()
                        + ". Declare the innerclass as static to make construction possible.");
    }
    try {
        Constructor<T> constructor = type.getDeclaredConstructor(argumentTypes);
        if (bypassAccessibility) {
            constructor.setAccessible(true);
        }
        return constructor.newInstance(arguments);

    } catch (InvocationTargetException e) {
        throw new UnitilsException("Error while trying to create object of class " + type.getName(),
                e.getCause());

    } catch (Exception e) {
        throw new UnitilsException("Error while trying to create object of class " + type.getName(), e);
    }
}

From source file:org.evosuite.setup.TestUsageChecker.java

public static boolean canUse(Class<?> c) {
    //if (Throwable.class.isAssignableFrom(c))
    //   return false;
    if (Modifier.isPrivate(c.getModifiers()))
        return false;

    if (!Properties.USE_DEPRECATED && c.isAnnotationPresent(Deprecated.class)) {
        final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

        if (Properties.hasTargetClassBeenLoaded() && !c.equals(targetClass)) {
            logger.debug("Skipping deprecated class " + c.getName());
            return false;
        }/*from w w  w.j  a  va  2s.  com*/
    }

    if (c.isAnonymousClass()) {
        return false;
    }

    if (c.getName().startsWith("junit"))
        return false;

    if (TestClusterUtils.isEvoSuiteClass(c) && !MockList.isAMockClass(c.getCanonicalName())) {
        return false;
    }

    if (c.getEnclosingClass() != null) {
        if (!canUse(c.getEnclosingClass()))
            return false;
    }

    if (c.getDeclaringClass() != null) {
        if (!canUse(c.getDeclaringClass()))
            return false;
    }

    // If the SUT is not in the default package, then
    // we cannot import classes that are in the default
    // package
    if (!c.isArray() && !c.isPrimitive() && !Properties.CLASS_PREFIX.isEmpty() && !c.getName().contains(".")) {
        return false;
    }

    if (c.getName().contains("EnhancerByMockito")) {
        return false;
    }

    // TODO: This should be unnecessary if Java reflection works...
    // This is inefficient
    if (TestClusterUtils.isAnonymousClass(c.getName())) {
        String message = c + " looks like an anonymous class, ignoring it (although reflection says "
                + c.isAnonymousClass() + ") " + c.getSimpleName();
        LoggingUtils.logWarnAtMostOnce(logger, message);
        return false;
    }

    if (Modifier.isPublic(c.getModifiers())) {
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(c.getModifiers())) {
        //              && !Modifier.isProtected(c.getModifiers())) {
        String packageName = ClassUtils.getPackageName(c);
        if (packageName.equals(Properties.CLASS_PREFIX)) {
            return true;
        }
    }

    logger.debug("Not public");
    return false;
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

@Inject
public void initSendMailCron() {
    if (!cronEnabled.booleanValue()) {
        return;//from  w w  w.j  ava 2 s  .co m
    }
    try {
        transport = session.getTransport("smtp");
    } catch (Exception ex) {
        logger.error("Could not initialize SMTP transport", ex);
        throw new IllegalStateException(ex);
    }
    try {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = new JobDetail("sendEmailJob", "sendEmailPoll", SendEmailJob.class);
        Trigger trigger = new DateIntervalTrigger("sendEmailTrigger", "sendEmailPoll",
                DateIntervalTrigger.IntervalUnit.SECOND, period.intValue());
        scheduler.setJobFactory(new JobFactory() {

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