List of usage examples for java.lang.reflect Modifier isPrivate
public static boolean isPrivate(int mod)
From source file:com.judoscript.jamaica.parser.JamaicaDumpVisitor.java
static void printAccessFlags(int flags) { if (Modifier.isPublic(flags)) out.print("public "); else if (Modifier.isProtected(flags)) out.print("protected "); else if (Modifier.isPrivate(flags)) out.print("private "); if (Modifier.isAbstract(flags)) out.print("abstract "); if (Modifier.isFinal(flags)) out.print("final "); if (Modifier.isNative(flags)) out.print("native "); if (Modifier.isStatic(flags)) out.print("static "); if (Modifier.isStrict(flags)) out.print("strict "); if (Modifier.isSynchronized(flags)) out.print("synchronized "); if (Modifier.isTransient(flags)) out.print("transient "); if (Modifier.isVolatile(flags)) out.print("volative "); }
From source file:org.evosuite.setup.TestUsageChecker.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: " + m.toString()); return false; }/* w ww .j av a 2 s . com*/ if (m.isSynthetic()) { logger.debug("Excluding synthetic method: " + m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !m.getDeclaringClass().equals(targetClass)) { logger.debug("Excluding deprecated method " + m.getName()); return false; } } if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Before.class) || m.isAnnotationPresent(BeforeClass.class) || m.isAnnotationPresent(After.class) || m.isAnnotationPresent(AfterClass.class)) { logger.debug("Excluding test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteTest.class)) { logger.debug("Excluding EvoSuite test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation " + m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && (!canUse(m.getReturnType()) || !canUse(m.getGenericReturnType()))) { return false; } for (java.lang.reflect.Type paramType : m.getGenericParameterTypes()) { if (!canUse(paramType)) return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode")) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (!m.getDeclaringClass().equals(targetClass)) return false; else { if (GraphPool.getInstance(ownerClass.getClassLoader()).getActualCFG(Properties.TARGET_CLASS, m.getName() + Type.getMethodDescriptor(m)) == null) { // Don't cover generated hashCode // TODO: This should work via annotations return false; } } } // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset method"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { TestClusterUtils.makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { TestClusterUtils.makeAccessible(m); return true; } } return false; }
From source file:org.apache.hadoop.fs.TestHarFileSystem.java
@Test public void testInheritedMethodsImplemented() throws Exception { int errors = 0; for (Method m : FileSystem.class.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers()) || Modifier.isPrivate(m.getModifiers()) || Modifier.isFinal(m.getModifiers())) { continue; }// w w w.j av a2 s. c om try { MustNotImplement.class.getMethod(m.getName(), m.getParameterTypes()); try { HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes()); LOG.error("HarFileSystem MUST not implement " + m); errors++; } catch (NoSuchMethodException ex) { // Expected } } catch (NoSuchMethodException exc) { try { HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes()); } catch (NoSuchMethodException exc2) { LOG.error("HarFileSystem MUST implement " + m); errors++; } } } assertTrue((errors + " methods were not overridden correctly - see log"), errors <= 0); }
From source file:name.yumaa.ChromeLogger4J.java
/** * Converts an object to a better format for logging * @param object variable to conver//from ww w.j ava 2 s .c om * @param depth recursion depth * @return converted object, ready to put to JSON */ private Object convert(Object object, int depth) { // *** return simple types as is *** if (object == null || object instanceof String || object instanceof Number || object instanceof Boolean) return object; // *** other simple types *** if (object instanceof Character || object instanceof StringBuffer || object instanceof StringBuilder || object instanceof Currency || object instanceof Date || object instanceof Locale) return object.toString(); if (object instanceof Calendar) return ((Calendar) object).getTime().toString(); if (object instanceof SimpleDateFormat) return ((SimpleDateFormat) object).toPattern(); // check recursion depth if (depth > this.depth) return "d>" + this.depth; // mark this object as processed so we don't convert it twice and it // also avoid recursion when objects refer to each other processed.add(object); // *** not so simple types, but we can foreach it *** if (object instanceof Map) { JSONObject jobject = new JSONObject(); for (Object key : ((Map<Object, Object>) object).keySet()) { Object value = ((Map<Object, Object>) object).get(key); addValue(jobject, key.toString(), value, depth); } return jobject; } if (object instanceof Collection) { JSONArray jobject = new JSONArray(); for (Object value : (Collection<Object>) object) addValue(jobject, value, depth); return jobject; } if (object instanceof Iterable) { JSONArray jobject = new JSONArray(); for (Object value : (Iterable<Object>) object) addValue(jobject, value, depth); return jobject; } if (object instanceof Object[]) { JSONArray jobject = new JSONArray(); for (Object value : (Object[]) object) addValue(jobject, value, depth); return jobject; } // *** object of unknown type *** JSONObject jobject = new JSONObject(); Class<?> cls = object.getClass(); jobject.put("___class_name", cls.getName()); // add the class name jobject.put("___toString()", object.toString()); // and to string representation if (!this.reflect) return jobject; // get all properties using reflection if (this.reflectfields) { try { for (Field field : cls.getDeclaredFields()) { Boolean access = field.isAccessible(); field.setAccessible(true); int mod = field.getModifiers(); String key = getKey(mod, field.getName()); Object value; try { value = field.get(object); } catch (Exception e) { value = e.toString(); } field.setAccessible(access); if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod))) continue; if (!this.reflectstatic && Modifier.isStatic(mod)) continue; addValue(jobject, key, value, depth); } } catch (SecurityException e) { } } // get all methods using reflection if (this.reflectmethods) { try { JSONObject methods = new JSONObject(); for (Method method : cls.getDeclaredMethods()) { Boolean access = method.isAccessible(); method.setAccessible(true); Class<?>[] params = method.getParameterTypes(); StringBuilder parameters = new StringBuilder(""); for (int i = 0, j = params.length; i < j; i++) { parameters.append(params[i].getName()); if (i + 1 < j) parameters.append(", "); } int mod = method.getModifiers(); String key = getKey(mod, method.getName() + "(" + parameters.toString() + ")"); String value = method.getReturnType().getName(); method.setAccessible(access); if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod))) continue; if (!this.reflectstatic && Modifier.isStatic(mod)) continue; methods.put(key, value); } jobject.put("___methods", methods); } catch (SecurityException e) { } } return jobject; }
From source file:com.autobizlogic.abl.util.BeanUtil.java
private static Field getFieldFromClass(Class<?> cls, String fieldName, Class<?> argClass, boolean onlyProtectedAndHigher) { Field[] allFields = cls.getDeclaredFields(); for (Field field : allFields) { if (!field.getName().equals(fieldName)) continue; int modifiers = field.getModifiers(); if (onlyProtectedAndHigher && Modifier.isPrivate(modifiers)) continue; if (argClass != null) { Class<?> genericType = getGenericType(field.getType()); if (!genericType.isAssignableFrom(argClass)) { String extraInfo = ""; // If the two classes have the same name, it's probably a classloader problem, // so we generate more informative output to help debug if (field.getType().getName().equals(argClass.getName())) { extraInfo = ". It looks like the two classes have the same name, so this is " + "probably a classloader issue. The bean field's class comes from " + field.getType().getClassLoader() + ", the other class comes from " + argClass.getClassLoader(); }/* ww w . j ava2s .co m*/ throw new RuntimeException("Bean field " + fieldName + " of class " + cls.getName() + " is of the wrong type (" + field.getType().getName() + ") for the given argument, " + "which is of type " + argClass.getName() + extraInfo); } } return field; } return null; }
From source file:adalid.core.EntityAtlas.java
@SuppressWarnings("deprecation") void initialiseFields(Class<?> clazz) { track("initialiseFields", _declaringArtifact, clazz.getSimpleName()); Class<?> c;//from w w w . j a v a2s .com int d, r; String name; String key; String pattern = "there are several fields for operation {0}"; String message; Class<?> type; Class<?> decl; Class<?> operationClass; Field operationField; int modifiers; boolean restricted; Object o; int depth = _declaringArtifact.depth(); int round = _declaringArtifact.round(); Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class, NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class }; Class<?> dac = _declaringArtifact.getClass(); Class<?> top = Entity.class; int i = ArrayUtils.indexOf(classes, clazz); if (i != ArrayUtils.INDEX_NOT_FOUND) { c = classes[i]; for (Field field : XS1.getFields(dac, top)) { field.setAccessible(true); logger.trace(field); name = field.getName(); type = field.getType(); decl = field.getDeclaringClass(); if (!c.isAssignableFrom(type)) { continue; } if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) { continue; } // TODO: extension handling if (field.isAnnotationPresent(Extension.class) && Entity.class.isAssignableFrom(type)) { // if (!dac.equals(decl) || !dac.isAssignableFrom(type)) { // continue; // } continue; } modifiers = type.getModifiers(); if (NamedValue.class.isAssignableFrom(type) || Expression.class.isAssignableFrom(type)) { restricted = false; } else { restricted = type.isInterface() || Modifier.isAbstract(modifiers); } restricted = restricted || !Modifier.isPublic(modifiers); if (restricted) { continue; } modifiers = field.getModifiers(); restricted = Modifier.isPrivate(modifiers); if (restricted) { continue; } restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers); if (restricted) { continue; } if (Operation.class.isAssignableFrom(type)) { key = type.getSimpleName(); operationClass = _operationClasses.get(key); if (operationClass != null) { operationField = _operationFields.get(key); if (operationField == null) { _operationFields.put(key, field); } else { message = MessageFormat.format(pattern, operationClass.getName()); logger.warn(message); TLC.getProject().getParser().increaseWarningCount(); } } } String errmsg = "failed to create a new instance of field \"" + field + "\" at " + _declaringArtifact; try { o = field.get(_declaringArtifact); if (o == null) { logger.debug(message(type, name, o, depth, round)); o = XS1.initialiseField(_declaringArtifact, field); if (o == null) { logger.debug(message(type, name, o, depth, round)); // throw new RuntimeException(message(type, name, o, depth, round)); } else { logger.debug(message(type, name, o, depth, round)); field.set(_declaringArtifact, o); } } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new InstantiationRuntimeException(errmsg, ex); } } } }
From source file:name.yumaa.ChromeLogger4J.java
/** * Returns a nicely formatted key of the field or method name * @param mod .getModifiers()//from ww w.ja v a 2 s.c o m * @param end key ending * @return class member keys, converted to string */ private String getKey(int mod, String end) { StringBuilder key = new StringBuilder(""); if (Modifier.isPublic(mod)) key.append("public "); if (Modifier.isPrivate(mod)) key.append("private "); if (Modifier.isProtected(mod)) key.append("protected "); if (Modifier.isStatic(mod)) key.append("static "); if (Modifier.isTransient(mod)) key.append("transient "); if (Modifier.isVolatile(mod)) key.append("volatile "); if (Modifier.isFinal(mod)) key.append("final "); if (Modifier.isSynchronized(mod)) key.append("synchronized "); return key.append(end).toString(); }
From source file:com.pwn9.pwnchat.config.ConfigObject.java
protected boolean doSkip(Field field) { return Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()) || Modifier.isPrivate(field.getModifiers()); }
From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java
private void ensureNoProtectedOrPrivateMethods(ModelSchemaExtractionContext<?> extractionContext, Class<?> typeClass) { Class<?> superClass = typeClass.getSuperclass(); if (superClass != null && !superClass.equals(Object.class)) { ensureNoProtectedOrPrivateMethods(extractionContext, superClass); }/*from ww w . j a va 2s . c o m*/ Iterable<Method> protectedAndPrivateMethods = Iterables .filter(Arrays.asList(typeClass.getDeclaredMethods()), new Predicate<Method>() { @Override public boolean apply(Method method) { int modifiers = method.getModifiers(); return !method.isSynthetic() && (Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers)); } }); if (!Iterables.isEmpty(protectedAndPrivateMethods)) { throw invalidMethods(extractionContext, "protected and private methods are not allowed", protectedAndPrivateMethods); } }
From source file:com.twinsoft.convertigo.beans.CheckBeans.java
private static void analyzeJavaClass(String javaClassName) { try {//w ww .j ava2 s . c om Class<?> javaClass = Class.forName(javaClassName); String javaClassSimpleName = javaClass.getSimpleName(); if (!DatabaseObject.class.isAssignableFrom(javaClass)) { //Error.NON_DATABASE_OBJECT.add(javaClassName); return; } nBeanClass++; String dboBeanInfoClassName = javaClassName + "BeanInfo"; MySimpleBeanInfo dboBeanInfo = null; try { dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance(); } catch (ClassNotFoundException e) { if (!Modifier.isAbstract(javaClass.getModifiers())) { Error.MISSING_BEAN_INFO .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")"); } return; } catch (Exception e) { e.printStackTrace(); return; } BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor(); // Check abstract class if (Modifier.isAbstract(javaClass.getModifiers())) { // Check icon (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check icon (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check display name if (!beanDescriptor.getDisplayName().equals("?")) { Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName); } // Check description if (!beanDescriptor.getShortDescription().equals("?")) { Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName); } } else { nBeanClassNotAbstract++; // Check bean declaration in database_objects.xml if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) { Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName); } // Check icon name policy (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); String expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (16x16) File iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check icon name policy (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (32x32) iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check display name if (beanDescriptor.getDisplayName().equals("?")) { Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName); } // Check description if (beanDescriptor.getShortDescription().equals("?")) { Error.BEAN_MISSING_DESCRIPTION.add(javaClassName); } } // Check declared bean properties PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); try { javaClass.getDeclaredField(propertyName); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { try { // Try to find it in the upper classes javaClass.getField(propertyName); } catch (SecurityException e1) { // printStackTrace(); } catch (NoSuchFieldException e1) { Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName); } } } Method[] methods = javaClass.getDeclaredMethods(); List<Method> listMethods = Arrays.asList(methods); List<String> listMethodNames = new ArrayList<String>(); for (Method method : listMethods) { listMethodNames.add(method.getName()); } Field[] fields = javaClass.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); // Ignore static fields (constants) if (Modifier.isStatic(fieldModifiers)) continue; String fieldName = field.getName(); String errorMessage = javaClassName + ": " + field.getName(); // Check bean info PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo); if (propertyDescriptor != null) { // Check bean property name policy if (!propertyDescriptor.getName().equals(fieldName)) { Error.PROPERTY_NAMING_POLICY.add(errorMessage); } String declaredGetter = propertyDescriptor.getReadMethod().getName(); String declaredSetter = propertyDescriptor.getWriteMethod().getName(); String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); String expectedGetter = "get" + formattedFieldName; String expectedSetter = "set" + formattedFieldName; // Check getter name policy if (!declaredGetter.equals(expectedGetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared getter: " + declaredGetter + "\n" + " Expected getter: " + expectedGetter); } // Check setter name policy if (!declaredSetter.equals(expectedSetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared setter: " + declaredSetter + "\n" + " Expected setter: " + expectedSetter); } // Check required private modifiers for bean property if (!Modifier.isPrivate(fieldModifiers)) { Error.PROPERTY_NOT_PRIVATE.add(errorMessage); } // Check getter if (!listMethodNames.contains(declaredGetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared getter not found: " + declaredGetter); } // Check setter if (!listMethodNames.contains(declaredSetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared setter not found: " + declaredGetter); } // Check non transient modifier if (Modifier.isTransient(fieldModifiers)) { Error.PROPERTY_TRANSIENT.add(errorMessage); } } else if (!Modifier.isTransient(fieldModifiers)) { Error.FIELD_NOT_TRANSIENT.add(errorMessage); } } } catch (ClassNotFoundException e) { System.out.println("ERROR on " + javaClassName); e.printStackTrace(); } }