List of usage examples for java.lang.reflect Modifier isPublic
public static boolean isPublic(int mod)
From source file:org.crazydog.util.spring.ClassUtils.java
/** * Given a method, which may come from an interface, and a target class used * in the current reflective invocation, find the corresponding target method * if there is one. E.g. the method may be {@code IFoo.bar()} and the * target class may be {@code DefaultFoo}. In this case, the method may be * {@code DefaultFoo.bar()}. This enables attributes on that method to be found. * <p><b>NOTE:</b> In contrast to {@link org.springframework.aop.support.AopUtils#getMostSpecificMethod}, * this method does <i>not</i> resolve Java 5 bridge methods automatically. * Call {@link org.springframework.core.BridgeMethodResolver#findBridgedMethod} * if bridge method resolution is desirable (e.g. for obtaining metadata from * the original method definition).//from w w w. j a v a 2s .c om * <p><b>NOTE:</b> Since Spring 3.1.1, if Java security settings disallow reflective * access (e.g. calls to {@code Class#getDeclaredMethods} etc, this implementation * will fall back to returning the originally provided method. * @param method the method to be invoked, which may come from an interface * @param targetClass the target class for the current invocation. * May be {@code null} or may not even implement the method. * @return the specific target method, or the original method if the * {@code targetClass} doesn't implement it or is {@code null} */ public static Method getMostSpecificMethod(Method method, Class<?> targetClass) { if (method != null && isOverridable(method, targetClass) && targetClass != null && !targetClass.equals(method.getDeclaringClass())) { try { if (Modifier.isPublic(method.getModifiers())) { try { return targetClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { return method; } } else { Method specificMethod = ReflectionUtils.findMethod(targetClass, method.getName(), method.getParameterTypes()); return (specificMethod != null ? specificMethod : method); } } catch (SecurityException ex) { // Security settings are disallowing reflective access; fall back to 'method' below. } } return method; }
From source file:com.glaf.core.util.ReflectUtils.java
public static boolean isPublicInstanceField(Field field) { return Modifier.isPublic(field.getModifiers()) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()) && !field.isSynthetic(); }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }/*from ww w. j a v a 2 s.c o m*/ final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List<Object> list = (List<Object>) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set<Object> set = (Set<Object>) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } Iterator<Object> it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } }
From source file:org.evosuite.setup.TestClusterGenerator.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)) { logger.debug("Skipping deprecated class {}", c.getName()); return false; }/*from w w w .j a v a 2 s . c om*/ if (c.isAnonymousClass()) { return false; } if (ANONYMOUS_MATCHER1.matcher(c.getName()).matches()) { logger.debug("{} looks like an anonymous class, ignoring it", c); return false; } if (ANONYMOUS_MATCHER2.matcher(c.getName()).matches()) { logger.debug("{} looks like an anonymous class, ignoring it", c); return false; } if (c.getName().startsWith("junit")) return false; if (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 (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:com.dianping.resource.io.util.ClassUtils.java
/** * Determine whether the given method is overridable in the given target class. * @param method the method to check/* ww w . j a va2 s . c o m*/ * @param targetClass the target class to check against */ private static boolean isOverridable(Method method, Class<?> targetClass) { if (Modifier.isPrivate(method.getModifiers())) { return false; } if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) { return true; } return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass)); }
From source file:eu.qualityontime.commons.MethodUtils.java
/** * <p>/*from w w w . ja va 2s . c om*/ * Return an accessible method (that is, one that can be invoked via * reflection) by scanning through the superclasses. If no such method can * be found, return <code>null</code>. * </p> * * @param clazz * Class to be checked * @param methodName * Method name of the method we wish to call * @param parameterTypes * The parameter type signatures */ private static Method getAccessibleMethodFromSuperclass(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes) { Class<?> parentClazz = clazz.getSuperclass(); while (parentClazz != null) { if (Modifier.isPublic(parentClazz.getModifiers())) { try { return parentClazz.getMethod(methodName, parameterTypes); } catch (final NoSuchMethodException e) { return null; } } parentClazz = parentClazz.getSuperclass(); } return null; }
From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java
private void testTests(final File dir) throws Exception { for (final File file : dir.listFiles()) { if (file.isDirectory()) { if (!".svn".equals(file.getName())) { testTests(file);//from w w w . ja va 2 s . c o m } } else { if (file.getName().endsWith(".java")) { final int index = new File("src/test/java").getAbsolutePath().length(); String name = file.getAbsolutePath(); name = name.substring(index + 1, name.length() - 5); name = name.replace(File.separatorChar, '.'); final Class<?> clazz; try { clazz = Class.forName(name); } catch (final Exception e) { continue; } name = file.getName(); if (name.endsWith("Test.java") || name.endsWith("TestCase.java")) { for (final Constructor<?> ctor : clazz.getConstructors()) { if (ctor.getParameterTypes().length == 0) { for (final Method method : clazz.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers()) && method.getAnnotation(Before.class) == null && method.getAnnotation(BeforeClass.class) == null && method.getAnnotation(After.class) == null && method.getAnnotation(AfterClass.class) == null && method.getAnnotation(Test.class) == null && method.getReturnType() == Void.TYPE && method.getParameterTypes().length == 0) { fail("Method '" + method.getName() + "' in " + name + " does not declare @Test annotation"); } } } } } } } } }
From source file:javadz.beanutils.MethodUtils.java
/** * <p>Find an accessible method that matches the given name and has compatible parameters. * Compatible parameters mean that every method parameter is assignable from * the given parameters./*from ww w . j a va 2 s . c om*/ * In other words, it finds a method with the given name * that will take the parameters given.<p> * * <p>This method is slightly undeterminstic since it loops * through methods names and return the first matching method.</p> * * <p>This method is used by * {@link * #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}. * * <p>This method can match primitive parameter by passing in wrapper classes. * For example, a <code>Boolean</code> will match a primitive <code>boolean</code> * parameter. * * @param clazz find method in this class * @param methodName find method with this name * @param parameterTypes find method with compatible parameters * @return The accessible method */ public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) { // trace logging Log log = LogFactory.getLog(MethodUtils.class); if (log.isTraceEnabled()) { log.trace("Matching name=" + methodName + " on " + clazz); } MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false); // see if we can find the method directly // most of the time this works and it's much faster try { // Check the cache first Method method = getCachedMethod(md); if (method != null) { return method; } method = clazz.getMethod(methodName, parameterTypes); if (log.isTraceEnabled()) { log.trace("Found straight match: " + method); log.trace("isPublic:" + Modifier.isPublic(method.getModifiers())); } setMethodAccessible(method); // Default access superclass workaround cacheMethod(md, method); return method; } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods int paramSize = parameterTypes.length; Method bestMatch = null; Method[] methods = clazz.getMethods(); float bestMatchCost = Float.MAX_VALUE; float myCost = Float.MAX_VALUE; for (int i = 0, size = methods.length; i < size; i++) { if (methods[i].getName().equals(methodName)) { // log some trace information if (log.isTraceEnabled()) { log.trace("Found matching name:"); log.trace(methods[i]); } // compare parameters Class[] methodsParams = methods[i].getParameterTypes(); int methodParamSize = methodsParams.length; if (methodParamSize == paramSize) { boolean match = true; for (int n = 0; n < methodParamSize; n++) { if (log.isTraceEnabled()) { log.trace("Param=" + parameterTypes[n].getName()); log.trace("Method=" + methodsParams[n].getName()); } if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) { if (log.isTraceEnabled()) { log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]); } match = false; break; } } if (match) { // get accessible version of method Method method = getAccessibleMethod(clazz, methods[i]); if (method != null) { if (log.isTraceEnabled()) { log.trace(method + " accessible version of " + methods[i]); } setMethodAccessible(method); // Default access superclass workaround myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes()); if (myCost < bestMatchCost) { bestMatch = method; bestMatchCost = myCost; } } log.trace("Couldn't find accessible method."); } } } } if (bestMatch != null) { cacheMethod(md, bestMatch); } else { // didn't find a match log.trace("No match found."); } return bestMatch; }
From source file:com.freetmp.common.util.ClassUtils.java
private static boolean isOverridable(Method method, Class<?> targetClass) { if (Modifier.isPrivate(method.getModifiers())) { return false; }//from w ww.j a v a 2 s .c om if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) { return true; } return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass)); }
From source file:com.jskaleel.xml.JSONObject.java
private void populateMap(Object bean) { Class klass = bean.getClass(); // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try {/* w w w . ja va2 s . com*/ Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key = ""; } else { key = name.substring(3); } } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); if (result != null) { this.map.put(key, wrap(result)); } } } } catch (Exception ignore) { } } }