Java Code Examples for java.lang.reflect.Modifier#isAbstract()

The following examples show how to use java.lang.reflect.Modifier#isAbstract() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConstructorFinder.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finds public constructor
 * that is declared in public class.
 *
 * @param type  the class that can have constructor
 * @param args  parameter types that is used to find constructor
 * @return object that represents found constructor
 * @throws NoSuchMethodException if constructor could not be found
 *                               or some constructors are found
 */
public static Constructor<?> findConstructor(Class<?> type, Class<?>...args) throws NoSuchMethodException {
    if (type.isPrimitive()) {
        throw new NoSuchMethodException("Primitive wrapper does not contain constructors");
    }
    if (type.isInterface()) {
        throw new NoSuchMethodException("Interface does not contain constructors");
    }
    if (Modifier.isAbstract(type.getModifiers())) {
        throw new NoSuchMethodException("Abstract class cannot be instantiated");
    }
    if (!Modifier.isPublic(type.getModifiers()) || !isPackageAccessible(type)) {
        throw new NoSuchMethodException("Class is not accessible");
    }
    PrimitiveWrapperMap.replacePrimitivesWithWrappers(args);
    Signature signature = new Signature(type, args);

    try {
        return CACHE.get(signature);
    }
    catch (SignatureException exception) {
        throw exception.toNoSuchMethodException("Constructor is not found");
    }
}
 
Example 2
Source File: PojoHandlersSetup.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private boolean shouldExpose(Method method) {
	boolean isUserDefined = !method.getDeclaringClass().equals(Object.class);

	int modifiers = method.getModifiers();

	boolean isAbstract = Modifier.isAbstract(modifiers);
	boolean isStatic = Modifier.isStatic(modifiers);
	boolean isPrivate = Modifier.isPrivate(modifiers);
	boolean isProtected = Modifier.isProtected(modifiers);

	if (isUserDefined && !isAbstract && !isStatic && !isPrivate && !isProtected && method.getAnnotations().length > 0) {
		for (Annotation ann : method.getAnnotations()) {
			String annoName = ann.annotationType().getName();
			if (CONTROLLER_ANNOTATIONS.contains(annoName)) {
				return true;
			}
		}
	}

	return false;
}
 
Example 3
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void generateSuperMethods() {
    for(final MethodInfo mi: methodInfos) {
        if(!Modifier.isAbstract(mi.method.getModifiers())) {
            generateSuperMethod(mi);
        }
    }
}
 
Example 4
Source File: InputConnectionInspector.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static boolean hasCommitCorrection(@NonNull final Class clazz) {
    try {
        final Method method = clazz.getMethod("commitCorrection", CorrectionInfo.class);
        return !Modifier.isAbstract(method.getModifiers());
    } catch (NoSuchMethodException e) {
        return false;
    }
}
 
Example 5
Source File: AbstractReflectivePortletTest.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns check methods to run as tests using java reflection.
 * The following rules are applied to select check methods:
 * <ul>
 *   <li>methods declared in this class or inherited from super class</li>
 *   <li>methods with modifier 'public' or 'protected', but not 'abstract'</li>
 *   <li>methods that starts with <code>check</code></li>
 * </ul>
 * @return a list of check methods.
 */
private List<Method> getCheckMethods(PortletRequest request) {
    List<Method> checkMethods = new ArrayList<Method>();
    DefaultTestPhase dtp = getClass().getAnnotation(DefaultTestPhase.class);
    String defaultPhase = dtp != null ? dtp.value() 
                                      : PortletRequest.RENDER_PHASE;
    String lifecyclePhase = (String) 
            request.getAttribute(PortletRequest.LIFECYCLE_PHASE);
    debugWithName("Default phase: " + defaultPhase);
    debugWithName("Lifecycle Phase: " + lifecyclePhase);
    for (Class<?> clazz = getClass();
            clazz != null && AbstractReflectivePortletTest.class.isAssignableFrom(clazz);
            clazz = clazz.getSuperclass()) {
        // debugWithName("Checking class: " + clazz.getName());
        Method[] methods = clazz.getDeclaredMethods();
        String phase;
        TestPhase testPhase;
        for (int i = 0; i < methods.length; i++) {
            int mod = methods[i].getModifiers();
            testPhase = methods[i].getAnnotation(TestPhase.class);
            phase = testPhase != null ? testPhase.value() : defaultPhase;
            if ((Modifier.isPublic(mod) || Modifier.isProtected(mod))
                   && lifecyclePhase.equals(phase)
                   && !Modifier.isAbstract(mod)
                   && methods[i].getName().startsWith("check")) {
                // debugWithName(" - got check method: " + methods[i].getName());
                debugWithName(" - got check method: " + methods[i].getName());
                checkMethods.add(methods[i]);
            }
        }
    }
    return checkMethods;
}
 
Example 6
Source File: ReflectionFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a direct MethodHandle for the {@code writeReplace} method on
 * a serializable class.
 * The single argument of {@link MethodHandle#invoke} is the serializable
 * object.
 *
 * @param cl the Serializable class
 * @return  a direct MethodHandle for the {@code writeReplace} method of the class or
 *          {@code null} if the class does not have a {@code writeReplace} method
 */
private MethodHandle getReplaceResolveForSerialization(Class<?> cl,
                                                       String methodName) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            Method m = defCl.getDeclaredMethod(methodName);
            if (m.getReturnType() != Object.class) {
                return null;
            }
            int mods = m.getModifiers();
            if (Modifier.isStatic(mods) | Modifier.isAbstract(mods)) {
                return null;
            } else if (Modifier.isPublic(mods) | Modifier.isProtected(mods)) {
                // fall through
            } else if (Modifier.isPrivate(mods) && (cl != defCl)) {
                return null;
            } else if (!packageEquals(cl, defCl)) {
                return null;
            }
            try {
                // Normal return
                m.setAccessible(true);
                return MethodHandles.lookup().unreflect(m);
            } catch (IllegalAccessException ex0) {
                // setAccessible should prevent IAE
                throw new InternalError("Error", ex0);
            }
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }
    return null;
}
 
Example 7
Source File: PojoSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public T createInstance() {
	if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
		return null;
	}
	try {
		T t = clazz.newInstance();
		initializeFields(t);
		return t;
	}
	catch (Exception e) {
		throw new RuntimeException("Cannot instantiate class.", e);
	}
}
 
Example 8
Source File: TestAnswer.java    From influxdb-java with MIT License 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  check(invocation);
  //call only non-abstract real method 
  if (Modifier.isAbstract(invocation.getMethod().getModifiers())) {
    return null;
  } else {
    return invocation.callRealMethod();
  }
}
 
Example 9
Source File: ObjectPayload.java    From ysoserial with MIT License 5 votes vote down vote up
public static Set<Class<? extends ObjectPayload>> getPayloadClasses () {
    final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName());
    final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class);
    for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) {
        Class<? extends ObjectPayload> pc = iterator.next();
        if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) {
            iterator.remove();
        }
    }
    return payloadTypes;
}
 
Example 10
Source File: DatatablesMetadataProvider.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @see DynamicFinderServicesImpl#getConcreteJavaType
 */
private JavaType getConcreteJavaType(final MemberDetails memberDetails) {
    Validate.notNull(memberDetails, "Member details required");
    JavaType javaType = null;
    for (final MemberHoldingTypeDetails memberHoldingTypeDetails : memberDetails
            .getDetails()) {
        if (Modifier.isAbstract(memberHoldingTypeDetails.getModifier())) {
            continue;
        }
        javaType = memberHoldingTypeDetails.getName();
    }
    return javaType;
}
 
Example 11
Source File: ModifierSupport.java    From sundrio with Apache License 2.0 4 votes vote down vote up
public boolean isAbstract() {
    return Modifier.isAbstract(modifiers);
}
 
Example 12
Source File: ObjectBuilder.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Create instance of <code>mapClass</code> from JSON representation. If
 * <code>mapClass</code> is interface then appropriate implementation of
 * interface will be returned.
 *
 * @param mapClass
 *         map type
 * @param genericType
 *         actual type of map
 * @param jsonObject
 *         source JSON object
 * @return map
 * @throws JsonException
 *         if any errors occurs
 */
@SuppressWarnings("unchecked")
public static <T extends Map<String, ?>> T createObject(Class<T> mapClass, Type genericType, JsonValue jsonObject)
        throws JsonException {
    if (jsonObject == null || jsonObject.isNull()) {
        return null;
    }
    Class mapValueClass;
    Type mapValueType;
    if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType)genericType;
        if (!String.class.isAssignableFrom((Class)parameterizedType.getActualTypeArguments()[0])) {
            throw new JsonException("Key of Map must be String. ");
        }
        mapValueType = parameterizedType.getActualTypeArguments()[1];
        if (mapValueType instanceof Class) {
            mapValueClass = (Class)mapValueType;
        } else if (mapValueType instanceof ParameterizedType) {
            mapValueClass = (Class)((ParameterizedType)mapValueType).getRawType();
        } else {
            throw new JsonException(
                    String.format("This type of Map can't be restored from JSON source.\nMap is parameterized by wrong Type: %s",
                                  parameterizedType));
        }
    } else {
        throw new JsonException("Map is not parameterized. Map<Sting, ?> is not supported.");
    }
    Constructor<? extends T> constructor;
    if (mapClass.isInterface() || Modifier.isAbstract(mapClass.getModifiers())) {
        constructor = getConstructor(findAcceptableMapImplementation(mapClass), Map.class);
    } else {
        constructor = getConstructor(mapClass, Map.class);
    }

    Types jsonMapValueType = getType(mapValueClass);
    HashMap<String, Object> sourceMap = new HashMap<>(jsonObject.size());
    Iterator<String> keys = jsonObject.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        JsonValue childJsonValue = jsonObject.getElement(key);
        if (jsonMapValueType == null) {
            sourceMap.put(key, createObject(mapValueClass, childJsonValue));
        } else {
            switch (jsonMapValueType) {
                case BYTE:
                case SHORT:
                case INT:
                case LONG:
                case FLOAT:
                case DOUBLE:
                case BOOLEAN:
                case CHAR:
                case STRING:
                case NULL:
                case ARRAY_BYTE:
                case ARRAY_SHORT:
                case ARRAY_INT:
                case ARRAY_LONG:
                case ARRAY_FLOAT:
                case ARRAY_DOUBLE:
                case ARRAY_BOOLEAN:
                case ARRAY_CHAR:
                case ARRAY_STRING:
                case CLASS:
                    sourceMap.put(key, createObjectKnownTypes(mapValueClass, childJsonValue));
                    break;
                case ARRAY_OBJECT:
                    sourceMap.put(key, createArray(mapValueClass, childJsonValue));
                    break;
                case COLLECTION:
                    sourceMap.put(key, createCollection(mapValueClass, mapValueType, childJsonValue));
                    break;
                case MAP:
                    sourceMap.put(key, createObject(mapValueClass, mapValueType, childJsonValue));
                    break;
                case ENUM:
                    sourceMap.put(key, createEnum(mapValueClass, childJsonValue));
                    break;
            }
        }
    }
    try {
        return constructor.newInstance(sourceMap);
    } catch (Exception e) {
        throw new JsonException(e.getMessage(), e);
    }
}
 
Example 13
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gathers methods that can be implemented or overridden from the specified type into this factory's
 * {@link #methodInfos} set. It will add all non-final, non-static methods that are either public or protected from
 * the type if the type itself is public. If the type is a class, the method will recursively invoke itself for its
 * superclass and the interfaces it implements, and add further methods that were not directly declared on the
 * class.
 * @param type the type defining the methods.
 */
private void gatherMethods(final Class<?> type) throws AdaptationException {
    if (Modifier.isPublic(type.getModifiers())) {
        final Method[] typeMethods = type.isInterface() ? type.getMethods() : type.getDeclaredMethods();

        for (final Method typeMethod: typeMethods) {
            final String name = typeMethod.getName();
            if(name.startsWith(SUPER_PREFIX)) {
                continue;
            }
            final int m = typeMethod.getModifiers();
            if (Modifier.isStatic(m)) {
                continue;
            }
            if (Modifier.isPublic(m) || Modifier.isProtected(m)) {
                // Is it a "finalize()"?
                if(name.equals("finalize") && typeMethod.getParameterCount() == 0) {
                    if(type != Object.class) {
                        hasExplicitFinalizer = true;
                        if(Modifier.isFinal(m)) {
                            // Must be able to override an explicit finalizer
                            throw new AdaptationException(Outcome.ERROR_FINAL_FINALIZER, type.getCanonicalName());
                        }
                    }
                    continue;
                }

                final MethodInfo mi = new MethodInfo(typeMethod);
                if (Modifier.isFinal(m) || isCallerSensitive(typeMethod)) {
                    finalMethods.add(mi);
                } else if (!finalMethods.contains(mi) && methodInfos.add(mi)) {
                    if (Modifier.isAbstract(m)) {
                        abstractMethodNames.add(mi.getName());
                    }
                    mi.setIsCanonical(this);
                }
            }
        }
    }
    // If the type is a class, visit its superclasses and declared interfaces. If it's an interface, we're done.
    // Needing to invoke the method recursively for a non-interface Class object is the consequence of needing to
    // see all declared protected methods, and Class.getDeclaredMethods() doesn't provide those declared in a
    // superclass. For interfaces, we used Class.getMethods(), as we're only interested in public ones there, and
    // getMethods() does provide those declared in a superinterface.
    if (!type.isInterface()) {
        final Class<?> superType = type.getSuperclass();
        if (superType != null) {
            gatherMethods(superType);
        }
        for (final Class<?> itf: type.getInterfaces()) {
            gatherMethods(itf);
        }
    }
}
 
Example 14
Source File: ClassDocImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return true if this class is abstract
 */
public boolean isAbstract() {
    return Modifier.isAbstract(getModifiers());
}
 
Example 15
Source File: AbstractComponentApiServlet.java    From baleen with Apache License 2.0 4 votes vote down vote up
private static boolean isAbstract(Class<?> clazz) {
  return Modifier.isAbstract(clazz.getModifiers());
}
 
Example 16
Source File: MemberName.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/** Utility method to query the modifier flags of this member. */
public boolean isAbstract() {
    return Modifier.isAbstract(flags);
}
 
Example 17
Source File: StandardClassMetadata.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAbstract() {
	return Modifier.isAbstract(this.introspectedClass.getModifiers());
}
 
Example 18
Source File: ReflectionNavigator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public boolean isAbstract(Class clazz) {
    return Modifier.isAbstract(clazz.getModifiers());
}
 
Example 19
Source File: StandardClassMetadata.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public boolean isAbstract() {
	return Modifier.isAbstract(this.introspectedClass.getModifiers());
}
 
Example 20
Source File: Reflections.java    From keycloak with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if a method is abstract
 *
 * @param method
 *
 * @return
 */
public static boolean isAbstract(Method method) {
    return Modifier.isAbstract(method.getModifiers());
}