Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

Returns the Java language modifiers for this class or interface, encoded in an integer.

Usage

From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java

@SuppressWarnings("unchecked")
public static <X> TypeInformation<X> getForClass(Class<X> clazz) {
    Validate.notNull(clazz);/*from   ww  w. j  a v a2s.c  o  m*/

    // check for abstract classes or interfaces
    if (Modifier.isInterface(clazz.getModifiers())
            || (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray())) {
        throw new InvalidTypesException("Interfaces and abstract classes are not valid types.");
    }

    // check for arrays
    if (clazz.isArray()) {

        // primitive arrays: int[], byte[], ...
        PrimitiveArrayTypeInfo<X> primitiveArrayInfo = PrimitiveArrayTypeInfo.getInfoFor(clazz);
        if (primitiveArrayInfo != null) {
            return primitiveArrayInfo;
        }

        // basic type arrays: String[], Integer[], Double[]
        BasicArrayTypeInfo<X, ?> basicArrayInfo = BasicArrayTypeInfo.getInfoFor(clazz);
        if (basicArrayInfo != null) {
            return basicArrayInfo;
        }

        // object arrays
        else {
            return ObjectArrayTypeInfo.getInfoFor(clazz);
        }
    }

    // check for writable types
    if (Writable.class.isAssignableFrom(clazz)) {
        return (TypeInformation<X>) WritableTypeInfo.getWritableTypeInfo((Class<? extends Writable>) clazz);
    }

    // check for basic types
    TypeInformation<X> basicTypeInfo = BasicTypeInfo.getInfoFor(clazz);
    if (basicTypeInfo != null) {
        return basicTypeInfo;
    }

    // check for subclasses of Value
    if (Value.class.isAssignableFrom(clazz)) {
        Class<? extends Value> valueClass = clazz.asSubclass(Value.class);
        return (TypeInformation<X>) ValueTypeInfo.getValueTypeInfo(valueClass);
    }

    // check for subclasses of Tuple
    if (Tuple.class.isAssignableFrom(clazz)) {
        throw new InvalidTypesException(
                "Type information extraction for tuples cannot be done based on the class.");
    }

    // return a generic type
    return new GenericTypeInfo<X>(clazz);
}

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

/**
 * Creates an instance of the given type
 * /*from   ww w  . ja  v a 2  s .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 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:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns 1 if the type is a collection,
 * -1 if it is definitely not// w  w  w  . j a va 2  s  .  com
 * and 0 if it may be a collection in some cases.
 * @param clazz to test
 * @return int
 */
public static int getCollectionHint(Class clazz) {
    if (clazz.isArray()) {
        return 1;
    }

    if (Collection.class.isAssignableFrom(clazz)) {
        return 1;
    }

    if (clazz.isPrimitive()) {
        return -1;
    }

    if (clazz.isInterface()) {
        return 0;
    }

    if (Modifier.isFinal(clazz.getModifiers())) {
        return -1;
    }

    return 0;
}

From source file:adalid.core.XS1.java

private static boolean isRestrictedFieldType(Class<?> fieldType) {
    int modifiers = fieldType.getModifiers();
    boolean b = fieldType.isPrimitive();
    b |= Modifier.isAbstract(modifiers) || !Modifier.isPublic(modifiers);
    b |= fieldType.isAnnotation();//from  w w w  .j  a  v  a  2s.  c  om
    b |= fieldType.isAnonymousClass();
    b |= fieldType.isArray();
    b |= fieldType.isEnum();
    b |= fieldType.isLocalClass();
    b |= fieldType.isInterface();
    return b;
}

From source file:org.apache.axis2.util.Utils.java

/**
 * Create a service object for a given service. The method first looks for
 * the {@link Constants#SERVICE_OBJECT_SUPPLIER} service parameter and if
 * this parameter is present, it will use the specified class to create the
 * service object. If the parameter is not present, it will create an
 * instance of the class specified by the {@link Constants#SERVICE_CLASS}
 * parameter./*from   www . jav a 2s  . c  o  m*/
 *
 * @param service
 *            the service
 * @return The service object or <code>null</code> if neither the
 *         {@link Constants#SERVICE_OBJECT_SUPPLIER} nor the
 *         {@link Constants#SERVICE_CLASS} parameter was found on the
 *         service, i.e. if the service doesn't specify how to create a
 *         service object. If the return value is non null, it will always
 *         be a newly created instance.
 * @throws AxisFault
 *             if an error occurred while attempting to instantiate the
 *             service object
 */
public static Object createServiceObject(final AxisService service) throws AxisFault {
    try {
        ClassLoader classLoader = service.getClassLoader();

        // allow alternative definition of makeNewServiceObject
        Parameter serviceObjectSupplierParam = service.getParameter(Constants.SERVICE_OBJECT_SUPPLIER);
        if (serviceObjectSupplierParam != null) {
            final Class<?> serviceObjectSupplierClass = Loader.loadClass(classLoader,
                    ((String) serviceObjectSupplierParam.getValue()).trim());
            if (ServiceObjectSupplier.class.isAssignableFrom(serviceObjectSupplierClass)) {
                ServiceObjectSupplier serviceObjectSupplier = org.apache.axis2.java.security.AccessController
                        .doPrivileged(new PrivilegedExceptionAction<ServiceObjectSupplier>() {
                            public ServiceObjectSupplier run()
                                    throws InstantiationException, IllegalAccessException {
                                return (ServiceObjectSupplier) serviceObjectSupplierClass.newInstance();
                            }
                        });
                return serviceObjectSupplier.getServiceObject(service);
            } else {
                // Prior to r439555 service object suppliers were actually defined by a static method
                // with a given signature defined on an arbitrary class. The ServiceObjectSupplier
                // interface was only introduced by r439555. We still support the old way, but
                // issue a warning inviting the user to provide a proper ServiceObjectSupplier
                // implementation.

                // Find static getServiceObject() method, call it if there
                final Method method = org.apache.axis2.java.security.AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Method>() {
                            public Method run() throws NoSuchMethodException {
                                return serviceObjectSupplierClass.getMethod("getServiceObject",
                                        AxisService.class);
                            }
                        });
                log.warn("The class specified by the " + Constants.SERVICE_OBJECT_SUPPLIER
                        + " property on service " + service.getName() + " does not implement the "
                        + ServiceObjectSupplier.class.getName() + " interface. This is deprecated.");
                return org.apache.axis2.java.security.AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                            public Object run() throws InvocationTargetException, IllegalAccessException,
                                    InstantiationException {
                                return method.invoke(serviceObjectSupplierClass.newInstance(),
                                        new Object[] { service });
                            }
                        });
            }
        } else {
            Parameter serviceClassParam = service.getParameter(Constants.SERVICE_CLASS);
            if (serviceClassParam != null) {
                final Class<?> serviceClass = Loader.loadClass(classLoader,
                        ((String) serviceClassParam.getValue()).trim());
                String className = ((String) serviceClassParam.getValue()).trim();
                Class serviceObjectMaker = Loader.loadClass(classLoader, className);
                if (serviceObjectMaker.getModifiers() != Modifier.PUBLIC) {
                    throw new AxisFault("Service class " + className + " must have public as access Modifier");
                }
                return org.apache.axis2.java.security.AccessController
                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                            public Object run() throws InstantiationException, IllegalAccessException {
                                return serviceClass.newInstance();
                            }
                        });
            } else {
                return null;
            }
        }
    } catch (Exception e) {
        throw AxisFault.makeFault(e);
    }
}

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

/**
 * Creates an instance of the given type
 * /* ww  w . ja  v a 2  s .  c  o m*/
 * @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:com.tmind.framework.pub.utils.MethodUtils.java

/**
 * <p>Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method.  If no such method
 * can be found, return <code>null</code>.</p>
 *
 * @param method The method that we wish to call
 *//* w  w w  . jav a2s. c  o m*/
public static Method getAccessibleMethod(Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return (null);
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return (null);
    }

    // If the declaring class is public, we are done
    Class clazz = method.getDeclaringClass();
    if (Modifier.isPublic(clazz.getModifiers())) {
        return (method);
    }

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(clazz, method.getName(), method.getParameterTypes());
    return (method);

}

From source file:org.mule.util.ClassUtils.java

public static boolean isConcrete(Class<?> clazz) {
    if (clazz == null) {
        throw new IllegalArgumentException("clazz may not be null");
    }//from   w  w w.  jav a 2  s.  c o m
    return !(clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()));
}

From source file:org.eclipse.skalli.testutil.PropertyTestUtil.java

private static Object assertExistsConstructor(Class<?> clazz, Map<Class<?>, String[]> requiredProperties,
        Map<String, Object> values) throws IllegalAccessException, IllegalArgumentException,
        InstantiationException, InvocationTargetException {
    Object instance = null;//  w  w w .  j  a  va 2s. co m
    String[] params = requiredProperties.get(clazz);
    if (params == null) {
        try {
            instance = clazz.newInstance();
        } catch (InstantiationException ex) {
            Assert.assertTrue(clazz.getName() + ": class without constructor must be abstract",
                    (clazz.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT);
        }
    } else {
        Class<?>[] paramTypes = new Class<?>[params.length];
        Object[] args = new Object[params.length];
        for (int i = 0; i < params.length; ++i) {
            Object arg = values.get(params[i]);
            Assert.assertNotNull(arg);
            args[i] = arg;
            paramTypes[i] = arg.getClass();
        }
        Constructor<?> c;
        try {
            c = clazz.getConstructor(paramTypes);
            instance = c.newInstance(args);
        } catch (NoSuchMethodException e) {
            Assert.fail(clazz.getName() + ": must have constructor " + clazz.getName() + "("
                    + Arrays.toString(paramTypes) + ")");
        } catch (InstantiationException e) {
            Assert.assertTrue(clazz.getName() + ": class is not instantiable",
                    (clazz.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT);
        }
    }
    return instance;
}

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.
 *///from   ww w.  j  av a  2  s .  co 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;
    }
}