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:org.apache.axis2.metadata.registry.MetadataFactoryRegistry.java

/**
 * This method will load a file, if it exists, that contains a list
 * of interfaces and custom implementations. This allows for non-
 * programmatic registration of custom interface implementations
 * with the MDQ layer.//from  w w w.j a v a  2  s . c  o m
 */
private static void loadConfigFromFile() {
    String pairSeparator = "|";
    try {
        ClassLoader classLoader = getContextClassLoader(null);
        URL url = null;
        url = classLoader.getResource(configurationFileLoc);
        if (url == null) {
            File file = new File(configurationFileLoc);
            url = file.toURL();
        }
        // the presence of this file is optional
        if (url != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found URL to MetadataFactoryRegistry configuration file: " + configurationFileLoc);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = reader.readLine();

            // the separator of the file is the '|' character
            // to the left of the separator will be the interface and
            // to the right will be the custom implementation
            if (line != null && line.indexOf("|") != -1) {
                String interfaceName = line.substring(0, line.indexOf(pairSeparator));
                String implName = line.substring(line.indexOf(pairSeparator) + 1, line.length());
                if (log.isDebugEnabled()) {
                    log.debug("For registered class: " + interfaceName + " the "
                            + "following implementation was found: " + implName);
                }
                Class intf = classLoader.loadClass(interfaceName);
                Class impl = classLoader.loadClass(implName);

                // if we could load both we need to register them with our
                // internal registry
                if (intf != null && impl != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Loaded both interface and implementation class: " + interfaceName + ":"
                                + implName);
                    }
                    if (impl.getEnclosingClass() == null) {
                        table.put(intf, impl.newInstance());
                    } else {
                        if (log.isWarnEnabled()) {
                            log.warn("The implementation class: " + impl.getClass().getName()
                                    + " could not be lregistered because it is an inner class. "
                                    + "In order to register file-based overrides, implementations "
                                    + "must be public outer classes.");
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not load both interface and implementation class: " + interfaceName
                                + ":" + implName);
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Did not find File for MetadataFactoryRegistry configuration " + "file: "
                            + configurationFileLoc);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Did not find URL for MetadataFactoryRegistry configuration " + "file: "
                        + configurationFileLoc);
            }
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("The MetadataFactoryRegistry could not process the configuration file: "
                    + configurationFileLoc + " because of the following error: " + t.toString());
        }
    }
}

From source file:Main.java

public static String isLocalType(Class<?> type, boolean allowNonStatic) {
    /* As per [JACKSON-187], GAE seems to throw SecurityExceptions
     * here and there... and GAE itself has a bug, too
     * (see []). Bah. So we need to catch some wayward exceptions on GAE
     *///from  ww  w  .j  a  v  a 2s  .  c om
    try {
        // one more: method locals, anonymous, are not good:
        if (type.getEnclosingMethod() != null) {
            return "local/anonymous";
        }

        /* But how about non-static inner classes? Can't construct
         * easily (theoretically, we could try to check if parent
         * happens to be enclosing... but that gets convoluted)
         */
        if (!allowNonStatic) {
            if (type.getEnclosingClass() != null) {
                if (!Modifier.isStatic(type.getModifiers())) {
                    return "non-static member class";
                }
            }
        }
    } catch (SecurityException e) {
    } catch (NullPointerException e) {
    }
    return null;
}

From source file:Main.java

/**
 * @since 1.9/*from  w  ww .ja  v a  2 s . co  m*/
 */
public static String isLocalType(Class<?> type, boolean allowNonStatic) {
    /* As per [JACKSON-187], GAE seems to throw SecurityExceptions
     * here and there... and GAE itself has a bug, too
     * (see []). Bah. So we need to catch some wayward exceptions on GAE
     */
    try {
        // one more: method locals, anonymous, are not good:
        if (type.getEnclosingMethod() != null) {
            return "local/anonymous";
        }

        /* But how about non-static inner classes? Can't construct
         * easily (theoretically, we could try to check if parent
         * happens to be enclosing... but that gets convoluted)
         */
        if (!allowNonStatic) {
            if (type.getEnclosingClass() != null) {
                if (!Modifier.isStatic(type.getModifiers())) {
                    return "non-static member class";
                }
            }
        }
    } catch (SecurityException e) {
    } catch (NullPointerException e) {
    }
    return null;
}

From source file:org.eclipse.wb.internal.core.parser.AbstractParseFactory.java

/**
 * @return the {@link Class} loaded using {@link ClassLoader} of given {@link AstEditor}. May
 *         return <code>null</code> if class can not be loaded.
 *//* ww w .  j  av  a2 s. c o m*/
protected static Class<?> getClass(AstEditor editor, ITypeBinding typeBinding) {
    try {
        ClassLoader classLoader = EditorState.get(editor).getEditorLoader();
        String componentClassName = AstNodeUtils.getFullyQualifiedName(typeBinding, true);
        Class<?> clazz = classLoader.loadClass(componentClassName);
        // we don't need inner Class
        if (clazz.getEnclosingClass() != null && !java.lang.reflect.Modifier.isStatic(clazz.getModifiers())) {
            return null;
        }
        // good Class
        return clazz;
    } catch (Throwable e) {
        return null;
    }
}

From source file:org.soybeanMilk.SbmUtils.java

/**
 * ???//from  w  w w .  j ava  2s  .  c  o  m
 * <pre>
 * class A&lt;T&gt;{}
 * class B extends A&lt;Integer&gt;{}
 * </pre>
 * <code>extractTypeVariablesInType(B.class, map)</code><code>map</code>
 * <pre>
 * T    -------&gt;    Integer
 * </pre>
 * @param source
 * @param container
 * @date 2012-5-14
 */
private static void extractTypeVariablesInType(Type source, Map<TypeVariable<?>, Type> variableTypesMap) {
    if (source == null)
        return;
    else if (source instanceof Class<?>) {
        Class<?> clazz = (Class<?>) source;

        //?
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        if (genericInterfaces != null) {
            for (Type t : genericInterfaces)
                extractTypeVariablesInType(t, variableTypesMap);
        }

        //
        Type genericSuperType = clazz.getGenericSuperclass();
        Class<?> superClass = clazz.getSuperclass();
        while (superClass != null && !Object.class.equals(superClass)) {
            extractTypeVariablesInType(genericSuperType, variableTypesMap);

            genericSuperType = superClass.getGenericSuperclass();
            superClass = superClass.getSuperclass();
        }

        //
        Class<?> outerClass = clazz;
        while (outerClass.isMemberClass()) {
            Type genericOuterType = outerClass.getGenericSuperclass();
            extractTypeVariablesInType(genericOuterType, variableTypesMap);

            outerClass = outerClass.getEnclosingClass();
        }
    } else if (source instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) source;

        if (isClassType(pt.getRawType())) {
            Type[] actualArgTypes = pt.getActualTypeArguments();
            TypeVariable<?>[] typeVariables = narrowToClass(pt.getRawType()).getTypeParameters();

            for (int i = 0; i < actualArgTypes.length; i++) {
                TypeVariable<?> var = typeVariables[i];
                Type value = actualArgTypes[i];

                //????
                if (value instanceof TypeVariable<?>) {
                    Type actual = variableTypesMap.get(value);

                    if (actual != null)
                        value = actual;
                }

                variableTypesMap.put(var, value);
            }
        }

        //??
        extractTypeVariablesInType(pt.getRawType(), variableTypesMap);
    }
}

From source file:org.eclipse.wb.android.internal.parser.AndroidDescriptionRulesProvider.java

/**
 * @return the key string to find a styleable in styleable map (attrs.xml).
 *//* ww w  .ja v a 2s  .com*/
private static String getStyleableKey(Class<?> componentClass) {
    // HACK: TableRow.LayoutParams has TableRow_Cell key
    if (ReflectionUtils.isSuccessorOf(componentClass, "android.widget.TableRow$LayoutParams")) {
        return "TableRow_Cell";
    }
    // for layout params it is like'LinearLayout_Layout', for ordinary view it is the short class name.
    String className = componentClass.getName();
    String classShortName = CodeUtils.getShortClass(className);
    String key;
    if (AndroidUtils.isLayoutParamClass(componentClass)) {
        Class<?> enclosingClass = componentClass.getEnclosingClass();
        // Transforms "LinearLayout" and "LayoutParams" into "LinearLayout_Layout".
        String xmlName = String.format("%1$s_%2$s", CodeUtils.getShortClass(enclosingClass.getName()),
                classShortName);
        key = xmlName.replaceFirst("Params$", "");
    } else {
        key = classShortName;
    }
    return key;
}

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

/**
 * Returns a map of the {@link CredentialsProvider} instances keyed by their name. A provider may have more than one
 * entry if there are inferred unique short nicknames.
 *
 * @return a map of the {@link CredentialsProvider} instances keyed by their name
 * @since 2.1.1//  www . j a  va 2 s. co m
 */
public static Map<String, CredentialsProvider> getProvidersByName() {
    Map<String, CredentialsProvider> providerByName = new TreeMap<String, CredentialsProvider>();
    for (CredentialsProvider r : ExtensionList.lookup(CredentialsProvider.class)) {
        providerByName.put(r.getClass().getName(), r);
        Class<?> clazz = r.getClass();
        while (clazz != null) {
            String shortName = clazz.getSimpleName();
            clazz = clazz.getEnclosingClass();
            String simpleName = shortName.toLowerCase(Locale.ENGLISH).replaceAll("(credentials|provider|impl)*",
                    "");
            if (StringUtils.isBlank(simpleName))
                continue;
            providerByName.put(shortName, providerByName.containsKey(shortName) ? CredentialsProvider.NONE : r);
            providerByName.put(simpleName,
                    providerByName.containsKey(simpleName) ? CredentialsProvider.NONE : r);
        }
    }
    for (Iterator<CredentialsProvider> iterator = providerByName.values().iterator(); iterator.hasNext();) {
        CredentialsProvider p = iterator.next();
        if (p == CredentialsProvider.NONE) {
            iterator.remove();
        }
    }
    return providerByName;
}

From source file:org.modelmapper.internal.util.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType) {
    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 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);
            buildTypeVariableMap(type.getGenericInterfaces(), map);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }//from  ww w . j a  v  a  2  s . c om

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

            type = type.getEnclosingClass();
        }

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

    return map;
}

From source file:antre.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType) {
    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 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);
            buildTypeVariableMap(type.getGenericInterfaces(), map);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }// w ww  .ja  v  a2 s  .  co m

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

            type = type.getEnclosingClass();
        }

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

    return map;
}

From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object fromJson(Class<?> clazz, Object json) throws JSONMappingException {
    if (json == null)
        return null;
    Object fromJson = null;/*from   w  w w  .java2  s.  co  m*/
    if (clazz == null) {
        try {
            fromJson = JSONEntity.fromJson(json);
        } catch (JSONException e) {
            e.printStackTrace();
            throw new JSONMappingException(e);
        }
    } else {
        Constructor<?> constructor;
        ;
        if (JSONEntity.class.isAssignableFrom(clazz)) { // A JSON Entity.
            Class<?> enclosingClass = clazz.getEnclosingClass();
            if (enclosingClass != null && (clazz.getModifiers() & Modifier.STATIC) == 0) { // it's a non static inner class
                try {
                    constructor = clazz.getDeclaredConstructor(enclosingClass, JSONObject.class);
                } catch (Exception e) {
                    throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e);
                }

                try {
                    /* we actually don't know the enclosing object...
                     * this will be a problem with inner classes that
                     * reference the enclosing class instance at 
                     * constructor time... although with json entities
                     * that should not happen. */
                    fromJson = constructor.newInstance(null, json);
                } catch (Exception e) {
                    throw new JSONMappingException(e);
                }
            } else { // static inner class
                try {
                    constructor = clazz.getDeclaredConstructor(JSONObject.class);
                } catch (Exception e) {
                    throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e);
                }

                try {
                    fromJson = constructor.newInstance(json);
                } catch (Exception e) {
                    throw new JSONMappingException("clazz = " + clazz.getName() + "; json = " + json.toString(),
                            e);
                }
            }
        } else if (clazz.isEnum()) {
            try {
                fromJson = Enum.valueOf((Class<Enum>) clazz, json.toString());
            } catch (Exception e) {
                fromJson = null;
            }
        } else {
            try {
                fromJson = JSONEntity.fromJson(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    if (clazz != null && !clazz.isAssignableFrom(fromJson.getClass()))
        throw new JSONMappingException("Was expeting a " + clazz.getName() + " but received a "
                + fromJson.getClass().getName() + " instead.");
    return fromJson;
}