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:com.flexive.shared.FxSharedUtils.java

/**
 * Returns the localized label for the given enum value. The enum translations are
 * stored in FxSharedMessages.properties and are standardized as
 * {@code FQCN.value},/*from   w ww. ja v  a2 s . c  o  m*/
 * e.g. {@code com.flexive.shared.search.query.ValueComparator.LIKE}.
 *
 * @param value the enum value to be translated
 * @param args  optional arguments to be replaced in the localized messages
 * @return the localized label for the given enum value
 */
public static FxString getEnumLabel(Enum<?> value, Object... args) {
    final Class<? extends Enum> valueClass = value.getClass();
    final String clsName;
    if (valueClass.getEnclosingClass() != null && Enum.class.isAssignableFrom(valueClass.getEnclosingClass())) {
        // don't include anonymous inner class definitions often used by enums in class name
        clsName = valueClass.getEnclosingClass().getName();
    } else {
        clsName = valueClass.getName();
    }
    return getMessage(SHARED_BUNDLE, clsName + "." + value.name(), args);
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String getModifiedClassName(Class cls) {
    Class enclosingClass = cls.getEnclosingClass();
    if (null != enclosingClass) {
        String en = enclosingClass.getCanonicalName();
        return en + cls.getCanonicalName().substring(en.length() + 1);
    }//from   w  w  w.  j  ava 2s.  co m
    return cls.getCanonicalName();
}

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

/**
 * {@inheritDoc}//  w  w  w .  ja v  a  2s. c om
 */
@Override
public String getDisplayName() {
    CredentialsStore store = getStore();
    if (this == store.getStoreAction()) {
        Class<?> c = store.getClass();
        while (c.getEnclosingClass() != null) {
            c = c.getEnclosingClass();
        }
        String name = c.getSimpleName().replaceAll("(?i)(Impl|Credentials|Provider|Store)+", "");
        if (StringUtils.isBlank(name)) {
            name = c.getSimpleName();
        }
        return StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(name), ' ');
    } else {
        return Messages.CredentialsStoreAction_DisplayName();
    }
}

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

/**
 * {@inheritDoc}//from w  ww.j  a va2 s.  c o  m
 */
@Override
public String getUrlName() {
    CredentialsStore store = getStore();
    if (this == store.getStoreAction()) {
        Class<?> c = store.getClass();
        while (c.getEnclosingClass() != null) {
            c = c.getEnclosingClass();
        }
        String name = c.getSimpleName().replaceAll("(?i)(Impl|Credentials|Provider|Store)+", "");
        if (StringUtils.isBlank(name)) {
            name = c.getSimpleName();
        }
        return StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(name), '-')
                .toLowerCase(Locale.ENGLISH);
    } else {
        return "credential-store";
    }
}

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private EntityModel createBeanEntity(Class clazz, RegistryNodeModel registryNodeModel,
        List<RelationshipModel> relationships, Map<String, EntityModel> models) {
    if (clazz == Object.class)
        return null;

    EntityModel model = models.get(clazz.getName());
    if (model != null)
        return model;

    String name = clazz.getSimpleName().replaceAll("\\B([A-Z]+)\\B", " $1");

    EntityModel entityModel;/*  ww  w .  j a v  a 2  s  .co m*/
    if (clazz.isMemberClass()) {
        entityModel = new SubEntityModel();
        name = "Nested " + name;
        registryNodeModel = models.get(clazz.getEnclosingClass().getName());
    } else {
        entityModel = new EntityModel();
    }

    models.put(clazz.getName(), entityModel);

    entityModel.setName(name);
    entityModel.setLookup(DiffUtils.lookup(registryNodeModel.getLookup(), name));
    entityModel.setPath(registryNodeModel.getLookup());
    entityModel.setAbstractEntity(Modifier.isAbstract(clazz.getModifiers()));
    entityModel.setTypeEntity(true);
    entityModel.setReverseEngineer(true);
    entityModel.setExtendedEntity(
            createBeanEntity(clazz.getSuperclass(), registryNodeModel, relationships, models));
    entityModel.setProtocol(EntityProtocol.HTTP);
    entityModel.setParent(registryNodeModel);

    Field[] declaredFields = clazz.getDeclaredFields();
    List<FieldModel> fields = new ArrayList<FieldModel>(declaredFields.length);

    for (Field field : declaredFields) {
        analyzeField(field.getName(), field.getGenericType(), TYPE, entityModel,
                field.getAnnotation(XmlElement.class), models, relationships, fields);

        XmlElements xmlElements = field.getAnnotation(XmlElements.class);
        if (xmlElements != null) {
            XmlElement[] elements = xmlElements.value();
            List<EntityModel> options = new ArrayList<EntityModel>(elements.length);
            RegistryNodeModel parent = clazz.isMemberClass() ? registryNodeModel.getParent()
                    : registryNodeModel;
            for (XmlElement element : elements) {
                if (element.type().isAnnotationPresent(XmlAccessorType.class)) {
                    EntityModel entity = createBeanEntity(element.type(), parent, relationships, models);
                    options.add(entity);
                }
            }
            FieldModel fieldModel = fields.get(fields.size() - 1);
            fieldModel.setOptions(options);
        }
    }

    entityModel.setFields(fields);

    return entityModel;
}

From source file:org.evosuite.setup.TestClusterGenerator.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)) {
        logger.debug("Skipping deprecated class {}", c.getName());
        return false;
    }//from   w ww.j  av  a2s .c  o m

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

    if (ANONYMOUS_MATCHER1.matcher(c.getName()).matches()) {
        logger.debug("{} looks like an anonymous class, ignoring it", c);
        return false;
    }

    if (ANONYMOUS_MATCHER2.matcher(c.getName()).matches()) {
        logger.debug("{} looks like an anonymous class, ignoring it", c);
        return false;
    }

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

    if (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 (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.github.wshackle.java4cpp.J4CppMain.java

private static String getCppClassName(Class clss) {
    String clssName = clss.getCanonicalName();
    String pkgs[] = clssName.split("\\.");
    String clssOnlyName = pkgs[pkgs.length - 1];
    Class enclosingClass = clss.getEnclosingClass();
    if (enclosingClass != null) {
        String enclosingClassName = enclosingClass.getCanonicalName();
        String enclosingPkgs[] = enclosingClassName.split("\\.");
        String enclosingName = enclosingPkgs[enclosingPkgs.length - 1];
        clssOnlyName = enclosingName + clssOnlyName;
    }//from w ww  . j  a v  a  2  s.  c  om
    return clssOnlyName;
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Determine the source file we're parsing.
 *///from   w ww. jav a  2  s.co m
protected File getSourceFile() {
    if (_file != null)
        return _file;

    Class<?> cls = _cls;
    while (cls.getEnclosingClass() != null)
        cls = cls.getEnclosingClass();

    String rsrc = StringUtils.replace(cls.getName(), ".", "/");
    ClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls));
    if (loader == null)
        loader = AccessController.doPrivileged(J2DoPrivHelper.getSystemClassLoaderAction());
    if (loader == null)
        return null;
    URL url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc + ".java"));
    if (url == null) {
        url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc + ".class"));
        if (url == null)
            return null;
    }
    try {
        _file = new File(url.toURI());
    } catch (URISyntaxException e) {
    } catch (IllegalArgumentException iae) {
        // this is thrown when the URI is non-hierarchical (aka JBoss)
    }
    return _file;
}

From source file:org.evosuite.testcase.ImportsTestCodeVisitor.java

/**
 * <p>//from  w  w  w .  ja  va 2 s .c o  m
 * getClassName
 * </p>
 *
 * @param clazz
 *            a {@link Class} object.
 * @return a {@link String} object.
 */
public String getClassName(Class<?> clazz) {
    if (classNames.containsKey(clazz))
        return classNames.get(clazz);

    if (clazz.isArray()) {
        return getClassName(clazz.getComponentType()) + "[]";
    }

    GenericClass c = new GenericClass(clazz);
    String name = c.getSimpleName();
    if (classNames.values().contains(name)) {
        name = clazz.getCanonicalName();
    } else {
        /*
         * If e.g. there is a foo.bar.IllegalStateException with
         * foo.bar being the SUT package, then we need to use the
         * full package name for java.lang.IllegalStateException
         */
        String fullName = Properties.CLASS_PREFIX + "." + name;
        if (!fullName.equals(clazz.getCanonicalName())) {
            try {
                if (ResourceList.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT())
                        .hasClass(fullName)) {
                    name = clazz.getCanonicalName();
                }
            } catch (IllegalArgumentException e) {
                // If the classpath is not correct, then we just don't check
                // because that cannot happen in regular EvoSuite use, only
                // from test cases
            }
        }
    }
    // Ensure outer classes are imported as well
    Class<?> outerClass = clazz.getEnclosingClass();
    if (outerClass != null) {
        String enclosingName = getClassName(outerClass);
        String simpleOuterName = outerClass.getSimpleName();
        if (simpleOuterName.equals(enclosingName)) {
            name = enclosingName + name.substring(simpleOuterName.length());
        } else {
            name = enclosingName + name.substring(name.lastIndexOf(simpleOuterName) + simpleOuterName.length());
        }
    }

    Class<?> declaringClass = clazz.getDeclaringClass();
    if (declaringClass != null) {
        getClassName(declaringClass);
    }

    // We can't use "Test" because of JUnit
    if (name.equals("Test")) {
        name = clazz.getCanonicalName();
    }
    classNames.put(clazz, name);

    return name;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String classToJNISignature(Class<?> clss) {
    if (boolean.class.isAssignableFrom(clss)) {
        return "Z";
    } else if (byte.class.isAssignableFrom(clss)) {
        return "B";
    } else if (char.class.isAssignableFrom(clss)) {
        return "C";
    } else if (short.class.isAssignableFrom(clss)) {
        return "S";
    } else if (int.class.isAssignableFrom(clss)) {
        return "I";
    } else if (long.class.isAssignableFrom(clss)) {
        return "J";
    } else if (float.class.isAssignableFrom(clss)) {
        return "F";
    } else if (double.class.isAssignableFrom(clss)) {
        return "D";
    } else if (void.class.isAssignableFrom(clss)) {
        return "V";
    } else if (clss.isArray()) {
        return "[" + classToJNISignature(clss.getComponentType());
    } else {/*  w  ww .j av  a2s .  com*/
        if (null != clss.getEnclosingClass()) {
            String s = classToJNISignature(clss.getEnclosingClass());
            String s1 = clss.getName();
            int dollarIndex = s1.indexOf('$');
            return s.substring(0, s.length() - 1) + s1.substring(dollarIndex) + ";";
        }
        return "L" + clss.getCanonicalName().replace(".", "/") + ";";
    }

}