Example usage for java.lang Class isInterface

List of usage examples for java.lang Class isInterface

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInterface();

Source Link

Document

Determines if the specified Class object represents an interface type.

Usage

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException//www .j  a va 2  s.  c  o m
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Check if a class is subclassing another class.
 * //w w w  .j a  v  a  2s. co  m
 * @param subClass
 *            the sub class
 * @param superClass
 *            the super class
 * @param matchNameOnly
 *            true to only do name string comparison, false also compares
 *            the class loader.
 * @return true if yes, false not
 */
public static boolean isSubClass(Class<?> subClass, final Class<?> superClass, final boolean matchNameOnly) {
    if (subClass.equals(superClass)) {
        return false;
    }
    if (superClass.equals(Object.class)) {
        return true;
    }
    Object result = traverseInheritance(subClass, superClass, subClass.isInterface(),
            new IClassVisitor<Object>() {

                public Object onVisit(Class<?> clazz) {
                    if (matchNameOnly) {
                        return clazz.getName().equals(superClass.getName()) ? new Object() : null;
                    } else {
                        return clazz.equals(superClass) ? new Object() : null;
                    }
                }

            });
    return result != null;
}

From source file:com.xiongyingqi.util.MethodInvoker.java

/**
 * Algorithm that judges the match between the declared parameter types of a candidate method
 * and a specific list of arguments that this method is supposed to be invoked with.
 * <p>Determines a weight that represents the class hierarchy difference between types and
 * arguments. A direct match, i.e. type Integer -> arg of class Integer, does not increase
 * the result - all direct matches means weight 0. A match between type Object and arg of
 * class Integer would increase the weight by 2, due to the superclass 2 steps up in the
 * hierarchy (i.e. Object) being the last one that still matches the required type Object.
 * Type Number and class Integer would increase the weight by 1 accordingly, due to the
 * superclass 1 step up the hierarchy (i.e. Number) still matching the required type Number.
 * Therefore, with an arg of type Integer, a constructor (Integer) would be preferred to a
 * constructor (Number) which would in turn be preferred to a constructor (Object).
 * All argument weights get accumulated.
 * <p>Note: This is the algorithm used by MethodInvoker itself and also the algorithm
 * used for constructor and factory method selection in Spring's bean container (in case
 * of lenient constructor resolution which is the default for regular bean definitions).
 *
 * @param paramTypes the parameter types to match
 * @param args       the arguments to match
 * @return the accumulated weight for all arguments
 *//*from   ww  w .j ava  2 s. co  m*/
public static int getTypeDifferenceWeight(Class<?>[] paramTypes, Object[] args) {
    int result = 0;
    for (int i = 0; i < paramTypes.length; i++) {
        if (!ClassUtils.isAssignableValue(paramTypes[i], args[i])) {
            return Integer.MAX_VALUE;
        }
        if (args[i] != null) {
            Class<?> paramType = paramTypes[i];
            Class<?> superClass = args[i].getClass().getSuperclass();
            while (superClass != null) {
                if (paramType.equals(superClass)) {
                    result = result + 2;
                    superClass = null;
                } else if (ClassUtils.isAssignable(paramType, superClass)) {
                    result = result + 2;
                    superClass = superClass.getSuperclass();
                } else {
                    superClass = null;
                }
            }
            if (paramType.isInterface()) {
                result = result + 1;
            }
        }
    }
    return result;
}

From source file:org.jgentleframework.context.JGentle.java

/**
 * Adds a config class/*from w  w w.  j a  v a2 s.co  m*/
 * 
 * @param interfaze
 *            type (<code>interface</code>) of <code>config class</code>.
 * @param clazz
 *            the <code>object class</code> of <code>config class</code>
 *            need to be added.
 * @return returns the previous <code>object class</code> of
 *         <code>config class</code> appropriate to <b><i>interfaze</i></b>
 *         if it existed, if not, returns <b>null</b>.
 */
@SuppressWarnings("unchecked")
public static <T> T addConfigClass(Class<T> interfaze, Class<? extends T> clazz) {

    Assertor.notNull(interfaze);
    Assertor.notNull(clazz);
    if (interfaze.equals(clazz)) {
        throw new JGentleRuntimeException("invalid arguments !");
    }
    if (!interfaze.isInterface()) {
        throw new JGentleRuntimeException(interfaze.toString() + " must be a interface.");
    }
    return (T) JGentle.configObjClassList.put(interfaze, clazz);
}

From source file:org.apache.hadoop.hbase.ipc.HBaseRPC.java

private static synchronized RpcEngine getProtocolEngine(Class protocol, Configuration conf) {
    RpcEngine engine = PROTOCOL_ENGINES.get(protocol);
    if (engine == null) {
        // check for a configured default engine
        Class<?> defaultEngine = conf.getClass(RPC_ENGINE_PROP, WritableRpcEngine.class);

        // check for a per interface override
        Class<?> impl = conf.getClass(RPC_ENGINE_PROP + "." + protocol.getName(), defaultEngine);
        LOG.debug("Using " + impl.getName() + " for " + protocol.getName());
        engine = (RpcEngine) ReflectionUtils.newInstance(impl, conf);
        if (protocol.isInterface())
            PROXY_ENGINES.put(Proxy.getProxyClass(protocol.getClassLoader(), protocol), engine);
        PROTOCOL_ENGINES.put(protocol, engine);
    }/*from w w w  .ja  v  a  2 s  .c  om*/
    return engine;
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Gets a list of classes in a given package. Note that interfaces are not returned.
 * /*  w  w w  .  j a  v a2s .c om*/
 * @param pkgname the package name.
 * @param suffix the ending text on name. eg "Resource.class"
 * @return the list of classes.
 */
public static ArrayList<Class<?>> getClassesForPackage(String pkgname, String suffix) throws IOException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    //Get a File object for the package
    File directory = null;
    String relPath = pkgname.replace('.', '/');
    Enumeration<URL> resources = OpenmrsClassLoader.getInstance().getResources(relPath);
    while (resources.hasMoreElements()) {

        URL resource = resources.nextElement();
        if (resource == null) {
            throw new RuntimeException("No resource for " + relPath);
        }

        try {
            directory = new File(resource.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(pkgname + " (" + resource
                    + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
                    e);
        } catch (IllegalArgumentException ex) {
            //ex.printStackTrace();
        }

        //If folder exists, look for all resource class files in it.
        if (directory != null && directory.exists()) {

            //Get the list of the files contained in the package
            String[] files = directory.list();

            for (int i = 0; i < files.length; i++) {

                //We are only interested in Resource.class files
                if (files[i].endsWith(suffix)) {

                    //Remove the .class extension
                    String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                    try {
                        Class<?> cls = Class.forName(className);
                        if (!cls.isInterface())
                            classes.add(cls);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } else {

            //Directory does not exist, look in jar file.
            try {
                String fullPath = resource.getFile();
                String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
                JarFile jarFile = new JarFile(jarPath);

                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();

                    String entryName = entry.getName();

                    if (!entryName.endsWith(suffix))
                        continue;

                    if (entryName.startsWith(relPath)
                            && entryName.length() > (relPath.length() + "/".length())) {
                        String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                        try {
                            Class<?> cls = Class.forName(className);
                            if (!cls.isInterface())
                                classes.add(cls);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException("ClassNotFoundException loading " + className);
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(
                        pkgname + " (" + directory + ") does not appear to be a valid package", e);
            }
        }
    }

    return classes;
}

From source file:edu.brown.utils.ClassUtil.java

/**
 * Get a set of all of the interfaces that the element_class implements
 * //from  ww  w.  j a v  a 2  s .  co  m
 * @param element_class
 * @return
 */
@SuppressWarnings("unchecked")
public static Collection<Class<?>> getInterfaces(Class<?> element_class) {
    Set<Class<?>> ret = ClassUtil.CACHE_getInterfaceClasses.get(element_class);
    if (ret == null) {
        // ret = new HashSet<Class<?>>();
        // Queue<Class<?>> queue = new LinkedList<Class<?>>();
        // queue.add(element_class);
        // while (!queue.isEmpty()) {
        // Class<?> current = queue.poll();
        // for (Class<?> i : current.getInterfaces()) {
        // ret.add(i);
        // queue.add(i);
        // } // FOR
        // } // WHILE
        ret = new HashSet<Class<?>>(ClassUtils.getAllInterfaces(element_class));
        if (element_class.isInterface())
            ret.add(element_class);
        ret = Collections.unmodifiableSet(ret);
        ClassUtil.CACHE_getInterfaceClasses.put(element_class, ret);
    }
    return (ret);
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Gets all the methods for a given class
 *
 * @param resultClass//  w  w  w  .  j av  a 2s  . c  o  m
 *            - Specifies the class name
 * @return - Returns all the methods
 */
@SuppressWarnings({ "rawtypes" })
public static Method[] getAllMethods(Class resultClass) {
    List<Method> methodList = new ArrayList<Method>();
    try {
        while (resultClass != null && !resultClass.isInterface() && !resultClass.isPrimitive()) {
            Method[] method = resultClass.getDeclaredMethods();
            for (int i = 0; i < method.length; i++) {
                method[i].setAccessible(true);
                methodList.add(method[i]);
            }
            if (!resultClass.getSuperclass().getName().equalsIgnoreCase("java.lang.Object")) {
                resultClass = resultClass.getSuperclass();
            } else {
                break;
            }
        }
    } catch (Exception ex) {
        log.error("ERROR: " + ex.getMessage());
    }
    Method[] methods = new Method[methodList.size()];
    for (int i = 0; i < methodList.size(); i++) {
        methods[i] = methodList.get(i);
    }
    return methods;
}

From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java

/**
 * Retrieves {@link JSONObject} class for deserialization.
 *
 * @param obj Object for which to get object class.
 * @param dfltCls Default class.//from w  w w.  jav a 2  s  . c o m
 * @return Class of the passed array.
 * @throws GridException Thrown if any error occurs while deserialization.
 */
private static Class getObjectClass(JSONObject obj, @Nullable Class dfltCls) throws GridException {
    assert obj != null;

    Class cls = null;

    if (obj.containsKey(AT_CLASS))
        cls = loadClass(obj, AT_CLASS);

    if (cls == null)
        if (dfltCls != null)
            cls = dfltCls;
        else
            cls = getDefaultClass(obj);

    assert cls != null;

    if (cls.isInterface() && Map.class.isAssignableFrom(cls))
        cls = HashMap.class;

    return cls;
}

From source file:cn.aposoft.util.spring.ReflectionUtils.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied
 * name and parameter types. Searches all superclasses up to {@code Object}.
 * <p>//from  w w  w  .  ja  va  2  s  .c  om
 * Returns {@code null} if no {@link Method} can be found.
 * 
 * @param clazz
 *            the class to introspect
 * @param name
 *            the name of the method
 * @param paramTypes
 *            the parameter types of the method (may be {@code null} to
 *            indicate any signature)
 * @return the Method object, or {@code null} if none found
 */
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                : getDeclaredMethods(searchType));
        for (Method method : methods) {
            if (name.equals(method.getName())
                    && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}