List of usage examples for java.lang Class getModifiers
@HotSpotIntrinsicCandidate public native int getModifiers();
From source file:org.evosuite.setup.TestUsageChecker.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)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !c.equals(targetClass)) { logger.debug("Skipping deprecated class " + c.getName()); return false; }/*w ww .j a v a2 s .c om*/ } if (c.isAnonymousClass()) { return false; } if (c.getName().startsWith("junit")) return false; if (TestClusterUtils.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 (c.getName().contains("EnhancerByMockito")) { return false; } // TODO: This should be unnecessary if Java reflection works... // This is inefficient if (TestClusterUtils.isAnonymousClass(c.getName())) { String message = c + " looks like an anonymous class, ignoring it (although reflection says " + c.isAnonymousClass() + ") " + c.getSimpleName(); LoggingUtils.logWarnAtMostOnce(logger, message); 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:uk.org.lidalia.sysoutslf4j.integration.CrossClassLoaderTestUtils.java
@SuppressWarnings("unchecked") public static <E> E moveToCurrentClassLoader(Class<E> destinationClass, Object target) { if (target.getClass().isPrimitive()) { return (E) target; } else if (destinationClass.isAssignableFrom(target.getClass())) { return (E) target; } else if (destinationClass.isInterface()) { return createProxyInterface(destinationClass, new ReflectionInvocationHandler(target)); } else if (target instanceof Enum<?>) { return (E) getLocalEnumInstance((Enum<?>) target, destinationClass); } else if (Modifier.isFinal(destinationClass.getModifiers())) { if (target instanceof Serializable) { return (E) moveToCurrentClassLoaderViaSerialization((Serializable) target); } else {//from www .ja va 2 s . co m return (E) target; } } else { return createProxyClass(destinationClass, new ReflectionInvocationHandler(target)); } }
From source file:org.paxml.util.ReflectUtils.java
/** * Check if a class is abstract class or interface. * /* ww w. j a v a 2 s . co m*/ * @param clazz * the class * @return true if yes, false not */ public static boolean isAbstract(Class<?> clazz) { return Modifier.isAbstract(clazz.getModifiers()); }
From source file:ReflectUtil.java
/** * <p>Attempts to find an accessible version of the method passed in, where accessible * is defined as the method itself being public and the declaring class being public. * Mostly useful as a workaround to the situation when * {@link PropertyDescriptor#getReadMethod()} and/or * {@link java.beans.PropertyDescriptor#getWriteMethod()} returns methods that are not * accessible (usually due to public implementations of interface methods in private * classes).</p>//from www .j a v a 2 s. c om * * <p>Checks the method passed in and if it already meets these criteria it is returned * immediately. In general this leads to very little performance overhead</p> * * <p>If the method does not meet the criteria then the class' interfaces are scanned * for a matching method. If one is not found, then the class' superclass hierarchy * is searched. Finally, if no matching method can be found the original method is * returned.</p> * * @param m a method that may or may not be accessible * @return either an accessible version of the same method, or the method passed in if * an accessible version cannot be found */ public static Method findAccessibleMethod(final Method m) { // If the passed in method is accessible, then just give it back. if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers())) return m; if (m.isAccessible()) return m; final Class<?> clazz = m.getDeclaringClass(); final String name = m.getName(); final Class<?>[] ptypes = m.getParameterTypes(); // Else, loop through the interfaces for the declaring class, looking for a // public version of the method that we can call for (Class<?> iface : clazz.getInterfaces()) { try { Method m2 = iface.getMethod(name, ptypes); if (m2.isAccessible()) return m2; if (isPublic(iface.getModifiers()) && isPublic(m2.getModifiers())) return m2; } catch (NoSuchMethodException nsme) { /* Not Unexpected. */ } } // Else loop through the superclasses looking for a public method Class<?> c = clazz.getSuperclass(); while (c != null) { try { Method m2 = c.getMethod(name, ptypes); if (m2.isAccessible()) return m2; if (isPublic(c.getModifiers()) && isPublic(m2.getModifiers())) return m2; } catch (NoSuchMethodException nsme) { /* Not Unexpected. */ } c = c.getSuperclass(); } // If we haven't found anything at this point, just give up! return m; }
From source file:com.addthis.codec.config.Configs.java
/** should be roughly analagous to a removed method */ private static ConfigValue resolveType(Class<?> type, ConfigValue configValue, PluginMap pluginMap) { String classField = pluginMap.classField(); if (configValue.valueType() != ConfigValueType.OBJECT) { if ((type == null) || Modifier.isAbstract(type.getModifiers()) || Modifier.isInterface(type.getModifiers())) { if (configValue.valueType() == ConfigValueType.LIST) { Class<?> arrayType = pluginMap.arraySugar(); if (arrayType != null) { ConfigObject aliasDefaults = pluginMap.aliasDefaults("_array"); String arrayFieldName = aliasDefaults.toConfig().getString("_primary"); String arraySugarName = pluginMap.getLastAlias("_array"); return ConfigFactory.empty().root() .withValue(classField, ConfigValueFactory.fromAnyRef(arraySugarName, pluginMap.category() + " array sugar : " + pluginMap.config().root().get("_array").origin().description())) .withValue(arrayFieldName, configValue).withFallback(aliasDefaults); }// w w w . ja v a 2 s . c o m } } return configValue; } ConfigObject root = (ConfigObject) configValue; ConfigValue classValue = root.get(classField); // normal, explicit typing if ((classValue != null) && (classValue.valueType() == ConfigValueType.STRING)) { String classValueString = (String) classValue.unwrapped(); ConfigObject aliasDefaults = pluginMap.aliasDefaults(classValueString); return root.withFallback(aliasDefaults); } if ((type == null) || Modifier.isAbstract(type.getModifiers()) || Modifier.isInterface(type.getModifiers())) { // single key as type if (root.size() == 1) { String onlyKey = root.keySet().iterator().next(); try { pluginMap.getClass(onlyKey); // make sure key is a valid type ConfigValue onlyKeyValue = root.values().iterator().next(); ConfigObject aliasDefaults = pluginMap.aliasDefaults(onlyKey); if (onlyKeyValue.valueType() != ConfigValueType.OBJECT) { if (aliasDefaults.get("_primary") != null) { onlyKeyValue = onlyKeyValue.atPath((String) aliasDefaults.get("_primary").unwrapped()) .root(); } else { throw new ConfigException.WrongType(onlyKeyValue.origin(), onlyKey, "OBJECT", onlyKeyValue.valueType().toString()); } } ConfigObject fieldValues = (ConfigObject) onlyKeyValue; return fieldValues .withValue(classField, ConfigValueFactory.fromAnyRef(onlyKey, "single key to type from " + root.origin().description())) .withFallback(aliasDefaults); } catch (ClassNotFoundException ignored) { } } // inlined type String matched = null; for (String alias : pluginMap.inlinedAliases()) { if (root.get(alias) != null) { if (matched != null) { String message = String.format( "no type specified, more than one key, and both %s and %s match for inlined types.", matched, alias); throw new ConfigException.Parse(root.origin(), message); } matched = alias; } } if (matched != null) { ConfigObject aliasDefaults = pluginMap.aliasDefaults(matched); ConfigValue inlinedValue = root.get(matched); String primaryField = (String) aliasDefaults.get("_primary").unwrapped(); ConfigObject fieldValues = root.toConfig().withValue(primaryField, inlinedValue).root() .withoutKey(matched).withFallback(aliasDefaults); return fieldValues.withValue(classField, ConfigValueFactory.fromAnyRef(matched, "inlined key to type from " + root.origin().description())); } // default type ConfigValue defaultObject = pluginMap.config().root().get("_default"); if (defaultObject != null) { String defaultName = pluginMap.getLastAlias("_default"); ConfigObject aliasDefaults = pluginMap.aliasDefaults("_default"); return root .withValue(classField, ConfigValueFactory.fromAnyRef(defaultName, pluginMap.category() + " default type : " + defaultObject.origin().description())) .withFallback(aliasDefaults); } } return root; }
From source file:org.apache.ddlutils.io.RoundtripTestBase.java
/** * Creates the test suite for the given test class which must be a sub class of * {@link RoundtripTestBase}. If the platform supports it, it will be tested * with both delimited and undelimited identifiers. * /*from w w w .j av a 2 s. com*/ * @param testedClass The tested class * @return The tests */ protected static TestSuite getTests(Class testedClass) { if (!RoundtripTestBase.class.isAssignableFrom(testedClass) || Modifier.isAbstract(testedClass.getModifiers())) { throw new DdlUtilsException("Cannot create parameterized tests for class " + testedClass.getName()); } TestSuite suite = new TestSuite(); try { Method[] methods = testedClass.getMethods(); PlatformInfo info = null; RoundtripTestBase newTest; for (int idx = 0; (methods != null) && (idx < methods.length); idx++) { if (methods[idx].getName().startsWith("test") && ((methods[idx].getParameterTypes() == null) || (methods[idx].getParameterTypes().length == 0))) { newTest = (RoundtripTestBase) testedClass.newInstance(); newTest.setName(methods[idx].getName()); newTest.setUseDelimitedIdentifiers(false); suite.addTest(newTest); if (info == null) { info = PlatformFactory.createNewPlatformInstance(newTest.getDatabaseName()) .getPlatformInfo(); } if (info.isDelimitedIdentifiersSupported()) { newTest = (RoundtripTestBase) testedClass.newInstance(); newTest.setName(methods[idx].getName()); newTest.setUseDelimitedIdentifiers(true); suite.addTest(newTest); } } } } catch (Exception ex) { throw new DdlUtilsException(ex); } return suite; }
From source file:net.neevek.android.lib.paginize.util.AnnotationUtils.java
private static Object getTargetListener(Class clazz, Object object, Map<Class, Object> targetListenerCache, Class targetListenerClass, String tag) throws InstantiationException, IllegalAccessException, InvocationTargetException { if (targetListenerClass == null || targetListenerClass == void.class) { return null; }/*from w w w. j a va2 s . c o m*/ Object targetListener = targetListenerCache.get(targetListenerClass); if (targetListener == null) { try { boolean isStatic = Modifier.isStatic(targetListenerClass.getModifiers()); if (isStatic) { Constructor ctor = targetListenerClass.getDeclaredConstructor(); ctor.setAccessible(true); targetListener = ctor.newInstance(); } else { Constructor ctor = targetListenerClass.getDeclaredConstructor(clazz); ctor.setAccessible(true); targetListener = ctor.newInstance(object); } targetListenerCache.put(targetListenerClass, targetListener); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("The 'listener' field: '" + targetListenerClass.getSimpleName() + "' in " + tag + " must contain a default constructor without arguments."); } } return targetListener; }
From source file:Main.java
public static String isLocalType(Class<?> type) { /* As per [JACKSON-187], GAE seems to throw SecurityExceptions * here and there... and GAE itself has a bug, too * (see []). Bah.//from ww w. j ava 2 s.c o m */ 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 (type.getEnclosingClass() != null) { if (!Modifier.isStatic(type.getModifiers())) { return "non-static member class"; } } } catch (SecurityException e) { } catch (NullPointerException e) { } return null; }
From source file:at.treedb.backup.Export.java
/** * Ignore abstract and some special class for default dump. * /* ww w. ja v a2 s . c o m*/ * @param clazz * @return {@code */ private static boolean isIgnoreClass(Class<?> clazz) { if (Modifier.isAbstract(clazz.getModifiers()) || clazz.equals(DBFSblock.class) || clazz.equals(DBinfo.class)) { return true; } return false; }
From source file:org.apache.usergrid.services.ServiceManager.java
@SuppressWarnings("unchecked") private static Class<Service> findClass(String classname) { Class<Service> cls; try {/*w ww . ja v a 2s .co m*/ logger.debug("Attempting to instantiate service class {}", classname); cls = (Class<Service>) Class.forName(classname); if (cls.isInterface()) { cls = (Class<Service>) Class.forName(classname.concat(IMPL)); } if ((cls != null) && !Modifier.isAbstract(cls.getModifiers())) { return cls; } } catch (ClassNotFoundException e1) { logger.debug("Could not load class", e1); } return null; }