List of usage examples for java.lang.reflect Modifier isFinal
public static boolean isFinal(int mod)
From source file:de.codesourcery.eve.apiclient.parsers.HttpAPIClientTest.java
private static Method findParserMethod(String name, Class<?>... args) throws Exception { try {/*from w w w.j av a2 s . c om*/ return AbstractResponseParser.class.getDeclaredMethod(name, args); } catch (Exception e) { try { return AbstractResponseParser.class.getMethod(name, args); } catch (Exception e2) { for (Method m : AbstractResponseParser.class.getMethods()) { if (!m.getName().equals(name)) { System.out.println("# Name mismatch: " + m); continue; } if (!ObjectUtils.equals(m.getParameterTypes(), args)) { System.out.println("# Param mismatch: " + m); continue; } final int modifiers = m.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers) || Modifier.isFinal(modifiers)) { System.out.println("# Modifier mismatch: " + m); continue; } return m; } throw e2; } } }
From source file:org.openmrs.util.OpenmrsClassLoader.java
/** * This clears any references this classloader might have that will prevent garbage collection. <br> * <br>//w ww.j a v a 2 s .c o m * Borrowed from Tomcat's WebappClassLoader#clearReferences() (not javadoc linked intentionally) <br> * The only difference between this and Tomcat's implementation is that this one only acts on * openmrs objects and also clears out static java.* packages. Tomcat acts on all objects and * does not clear our static java.* objects. * * @since 1.5 */ protected static void clearReferences() { // Unregister any JDBC drivers loaded by this classloader Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == getInstance()) { try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { log.warn("SQL driver deregistration failed", e); } } } // Null out any static or final fields from loaded classes, // as a workaround for apparent garbage collection bugs for (WeakReference<Class<?>> refClazz : getInstance().cachedClasses.values()) { if (refClazz == null) { continue; } Class<?> clazz = refClazz.get(); if (clazz != null && clazz.getName().contains("openmrs")) { // only clean up openmrs classes try { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) { continue; } if (Modifier.isStatic(mods)) { try { // do not clear the log field on this class yet if (clazz.equals(OpenmrsClassLoader.class) && "log".equals(field.getName())) { continue; } field.setAccessible(true); if (Modifier.isFinal(mods)) { if (!(field.getType().getName().startsWith("javax."))) { nullInstance(field.get(null)); } } else { field.set(null, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + clazz.getName()); } } } catch (Exception t) { if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } } } } } catch (Exception t) { if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } } } } // now we can clear the log field on this class OpenmrsClassLoader.log = null; getInstance().cachedClasses.clear(); }
From source file:org.jboss.dashboard.factory.Component.java
protected Field getField(Object obj, String propertyName) { try {/* www . j a v a 2 s.c om*/ Field field = obj.getClass().getField(propertyName); int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers) && !Modifier.isFinal(field.getModifiers())) { return field; } } catch (NoSuchFieldException e) { } if (log.isDebugEnabled()) { log.debug("Could not find a field for property " + propertyName + " in " + obj.getClass()); } return null; }
From source file:org.openlegacy.designtime.db.generators.support.DefaultDbPojoCodeModel.java
private void calculateFieldsProperties() { List<BodyDeclaration> members = mainType.getMembers(); for (BodyDeclaration bodyDeclaration : members) { if (bodyDeclaration instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration; List<VariableDeclarator> variables = fieldDeclaration.getVariables(); if (variables.size() > 0) { List<AnnotationExpr> fieldAnnotations = fieldDeclaration.getAnnotations(); String fieldName = variables.get(0).getId().getName(); Field field = new Field(fieldName, fieldDeclaration.getType().toString()); field.setPrimitiveType(TypesUtil.isPrimitive(fieldDeclaration.getType().toString())); if (fieldAnnotations != null && fieldAnnotations.size() > 0) { for (AnnotationExpr annotationExpr : fieldAnnotations) { if (JavaParserUtil.isOneOfAnnotationsPresent(annotationExpr, DbAnnotationConstants.DB_FIELD_ANNOTATION)) { DbAnnotationsParserUtils.loadDbFieldAnnotation(annotationExpr, field); if (!field.isPrimitiveType()) { field.setFieldTypeDefinition( AnnotationsParserUtils.loadEnumField(mainType, fieldDeclaration)); }//from ww w.ja v a2 s. com } if (JavaParserUtil.isOneOfAnnotationsPresent(annotationExpr, DbAnnotationConstants.DB_ID_ANNOTATION)) { field.setKey(true); } } } if (Modifier.isStatic(fieldDeclaration.getModifiers()) || Modifier.isFinal(fieldDeclaration.getModifiers())) { field.setStaticOrFinal(true); } fields.put(fieldName, field); } } } checkHasGetterAndSetter(members); }
From source file:com.sm.query.utils.QueryUtils.java
/** * @param field//from w w w . ja v a 2 s . c o m * @return true - for write able field */ public static boolean isSkipField(Field field) { int modifier = field.getModifiers(); if (Modifier.isFinal(modifier) || Modifier.isStatic(modifier) || Modifier.isNative(modifier) || Modifier.isTransient(modifier)) return true; else return false; }
From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryGeneratorTest.java
@Test public void validateContentOfErrorDataCollections() throws Exception { String errorDataCOllectionClassName = "org.ebayopensource.turmeric.test.errorlibrary.turmericruntime.ErrorDataCollection"; String sampleErrorName = "svc_factory_custom_ser_no_bound_type"; // Initialize testing paths MavenTestingUtils.ensureEmpty(testingdir); File rootDir = TestResourceUtil.copyResourceRootDir("errorLibrary/TestErrorLibrary", testingdir); File binDir = new File(rootDir, "bin"); File gensrcDir = new File(rootDir, "gen-src"); MavenTestingUtils.ensureDirExists(binDir); MavenTestingUtils.ensureDirExists(gensrcDir); // @formatter:off String pluginParameters[] = { "-gentype", "genTypeDataCollection", "-pr", rootDir.getAbsolutePath(), "-domain", "TurmericRuntime", "-errorlibname", "TestErrorLibrary" }; // @formatter:on performDirectCodeGen(pluginParameters); Class<?> errDataCollection = compileGeneratedFile(errorDataCOllectionClassName, gensrcDir, binDir); Assert.assertThat("errDataCollection", errDataCollection, notNullValue()); Assert.assertThat(errDataCollection.getName(), is(errorDataCOllectionClassName)); Field member = errDataCollection.getField(sampleErrorName); Assert.assertThat("member", member, notNullValue()); Assert.assertThat("member.type", member.getType().getName(), is(CommonErrorData.class.getName())); Assert.assertThat("member.isFinal", Modifier.isFinal(member.getModifiers()), is(true)); Assert.assertThat("member.isPublic", Modifier.isPublic(member.getModifiers()), is(true)); Assert.assertThat("member.isStatic", Modifier.isStatic(member.getModifiers()), is(true)); CommonErrorData edata = (CommonErrorData) member.get(null); Assert.assertThat("CommonErrorData", edata, notNullValue()); Assert.assertThat("CommonErrorData.category", edata.getCategory(), is(ErrorCategory.SYSTEM)); Assert.assertThat("CommonErrorData.severity", edata.getSeverity(), is(ErrorSeverity.ERROR)); Assert.assertThat("CommonErrorData.subdommain", edata.getSubdomain(), is("Config")); }
From source file:org.kuali.test.utils.Utils.java
/** * * @param clazz//from w ww .j a va2s . c o m * @param includeEmptyItem * @return */ public static String[] getXmlEnumerations(Class clazz, boolean includeEmptyItem) { List<String> retval = new ArrayList<String>(); Field[] fields = clazz.getDeclaredFields(); if (includeEmptyItem) { retval.add(""); } for (Field field : fields) { // looking for XMLBean enumerated types if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) { Class c = field.getType(); // if this is a static Enum inner class - that is what we are looking for if (c.getName().endsWith(ENUM_CHILD_CLASS)) { try { Object e = field.get(null); retval.add(e.toString()); } catch (Exception ex) { LOG.warn(ex.toString()); } } } } return retval.toArray(new String[retval.size()]); }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
/** * Throw appropriate exception if the given type is final. *///from w w w . j a va 2 s . com private static void assertNotFinal(Class type) { if (Modifier.isFinal(type.getModifiers())) throw new UnsupportedException(_loc.get("no-proxy-final", type)); }
From source file:org.evosuite.setup.TestClusterGenerator.java
/** * All public methods defined directly in the SUT should be covered * /* ww w. j a v a 2 s . co m*/ * TODO: What if we use instrument_parent? * * @param targetClass */ @SuppressWarnings("unchecked") private void initializeTargetMethods() throws RuntimeException, ClassNotFoundException { logger.info("Analyzing target class"); Class<?> targetClass = Properties.getTargetClass(); TestCluster cluster = TestCluster.getInstance(); Set<Class<?>> targetClasses = new LinkedHashSet<Class<?>>(); if (targetClass == null) { throw new RuntimeException("Failed to load " + Properties.TARGET_CLASS); } targetClasses.add(targetClass); addDeclaredClasses(targetClasses, targetClass); if (Modifier.isAbstract(targetClass.getModifiers())) { logger.info("SUT is an abstract class"); Set<Class<?>> subclasses = getConcreteClasses(targetClass, inheritanceTree); logger.info("Found {} concrete subclasses", subclasses.size()); targetClasses.addAll(subclasses); } // To make sure we also have anonymous inner classes double check inner classes using ASM ClassNode targetClassNode = DependencyAnalysis.getClassNode(Properties.TARGET_CLASS); Queue<InnerClassNode> innerClasses = new LinkedList<InnerClassNode>(); innerClasses.addAll(targetClassNode.innerClasses); while (!innerClasses.isEmpty()) { InnerClassNode icn = innerClasses.poll(); try { logger.debug("Loading inner class: {}, {},{}", icn.innerName, icn.name, icn.outerName); String innerClassName = ResourceList.getClassNameFromResourcePath(icn.name); Class<?> innerClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(innerClassName); //if (!canUse(innerClass)) // continue; // Sometimes strange things appear such as Map$Entry if (!targetClasses.contains(innerClass)) { // && !innerClassName.matches(".*\\$\\d+(\\$.*)?$")) { logger.info("Adding inner class {}", innerClassName); targetClasses.add(innerClass); ClassNode innerClassNode = DependencyAnalysis.getClassNode(innerClassName); innerClasses.addAll(innerClassNode.innerClasses); } } catch (Throwable t) { logger.error("Problem for {}. Error loading inner class: {}, {},{}: {}", Properties.TARGET_CLASS, icn.innerName, icn.name, icn.outerName, t); } } for (Class<?> clazz : targetClasses) { logger.info("Current SUT class: {}", clazz); if (!canUse(clazz)) { logger.info("Cannot access SUT class: {}", clazz); continue; } // Add all constructors for (Constructor<?> constructor : getConstructors(clazz)) { logger.info("Checking target constructor {}", constructor); String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getName(), "<init>", org.objectweb.asm.Type.getConstructorDescriptor(constructor)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(constructor)) { GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz); cluster.addTestCall(genericConstructor); // TODO: Add types! cluster.addGenerator(new GenericClass(clazz).getWithWildcardTypes(), genericConstructor); addDependencies(genericConstructor, 1); logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(), constructor.getName(), Type.getConstructorDescriptor(constructor)); } else { logger.debug("Constructor cannot be used: {}", constructor); } } // Add all methods for (Method method : getMethods(clazz)) { logger.info("Checking target method {}", method); String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getName(), method.getName(), org.objectweb.asm.Type.getMethodDescriptor(method)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(method, clazz)) { logger.debug("Adding method {}.{}{}", clazz.getName(), method.getName(), Type.getMethodDescriptor(method)); GenericMethod genericMethod = new GenericMethod(method, clazz); cluster.addTestCall(genericMethod); cluster.addModifier(new GenericClass(clazz).getWithWildcardTypes(), genericMethod); addDependencies(genericMethod, 1); GenericClass retClass = new GenericClass(method.getReturnType()); if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject()) cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod); } else { logger.debug("Method cannot be used: {}", method); } } for (Field field : getFields(clazz)) { logger.info("Checking target field {}", field); if (canUse(field, clazz)) { GenericField genericField = new GenericField(field, clazz); addDependencies(genericField, 1); cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(), genericField); logger.debug("Adding field {}", field); if (!Modifier.isFinal(field.getModifiers())) { logger.debug("Is not final"); cluster.addTestCall(new GenericField(field, clazz)); } else { logger.debug("Is final"); if (Modifier.isStatic(field.getModifiers()) && !field.getType().isPrimitive()) { logger.debug("Is static non-primitive"); /* * With this we are trying to cover such cases: * public static final DurationField INSTANCE = new MillisDurationField(); private MillisDurationField() { super(); } */ try { Object o = field.get(null); if (o == null) { logger.info("Field is not yet initialized: {}", field); } else { Class<?> actualClass = o.getClass(); logger.debug("Actual class is {}", actualClass); if (!actualClass.isAssignableFrom(genericField.getRawGeneratedType()) && genericField.getRawGeneratedType().isAssignableFrom(actualClass)) { GenericField superClassField = new GenericField(field, clazz); cluster.addGenerator(new GenericClass(actualClass), superClassField); } } } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else { logger.debug("Can't use field {}", field); } } analyzedClasses.add(clazz); // TODO: Set to generic type rather than class? cluster.getAnalyzedClasses().add(clazz); } if (Properties.INSTRUMENT_PARENT) { for (String superClass : inheritanceTree.getSuperclasses(Properties.TARGET_CLASS)) { try { Class<?> superClazz = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(superClass); dependencies.add(new Pair(0, superClazz)); } catch (ClassNotFoundException e) { logger.error("Problem for {}. Class not found: {}", Properties.TARGET_CLASS, superClass, e); } } } if (Properties.HANDLE_STATIC_FIELDS) { GetStaticGraph getStaticGraph = GetStaticGraphGenerator.generate(Properties.TARGET_CLASS); Map<String, Set<String>> staticFields = getStaticGraph.getStaticFields(); for (String className : staticFields.keySet()) { logger.info("Adding static fields to cluster for class {}", className); Class<?> clazz; try { clazz = getClass(className); } catch (ExceptionInInitializerError ex) { logger.debug("Class class init caused exception {}", className); continue; } if (clazz == null) { logger.debug("Class not found {}", className); continue; } if (!canUse(clazz)) continue; Set<String> fields = staticFields.get(className); for (Field field : getFields(clazz)) { if (!canUse(field, clazz)) continue; if (fields.contains(field.getName())) { if (!Modifier.isFinal(field.getModifiers())) { logger.debug("Is not final"); cluster.addTestCall(new GenericField(field, clazz)); } } } } PutStaticMethodCollector collector = new PutStaticMethodCollector(Properties.TARGET_CLASS, staticFields); Set<MethodIdentifier> methodIdentifiers = collector.collectMethods(); for (MethodIdentifier methodId : methodIdentifiers) { Class<?> clazz = getClass(methodId.getClassName()); if (clazz == null) continue; if (!canUse(clazz)) continue; Method method = getMethod(clazz, methodId.getMethodName(), methodId.getDesc()); if (method == null) continue; GenericMethod genericMethod = new GenericMethod(method, clazz); cluster.addTestCall(genericMethod); } } logger.info("Finished analyzing target class"); }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
private static boolean isProxyable(Class<?> cls) { int mod = cls.getModifiers(); if (Modifier.isFinal(mod)) return false; if (Modifier.isProtected(mod) || Modifier.isPublic(mod)) return true; // Default scoped class, we can only extend if it is in the same package as the generated proxy. Ideally // we'd fix the code gen portion and place proxies in the same pacakge as the types being proxied. if (cls.getPackage().getName().equals("org.apache.openjpa.util")) return true; return false; }