/** Sets the access flag of a member */ @Override protected void setAccessFlag(final Member m) { final int mods = m.getModifiers(); final Class c = m.getDeclaringClass(); final int cmods = c.getModifiers(); final String pkg = this.importationManager.getCurrentPackage(); final String mp = getPackageName(c); final boolean samePkg = pkg.equals(mp); if (Modifier.isPublic(cmods) || samePkg) { if (Modifier.isPublic(mods)) { ((AccessibleObject) m).setAccessible(true); } else if (Modifier.isProtected(mods)) { if (c.isAssignableFrom(this.declaringClass.getSuperclass()) || samePkg) { ((AccessibleObject) m).setAccessible(true); } } else if (!Modifier.isPrivate(mods)) { if (samePkg) { ((AccessibleObject) m).setAccessible(true); } } else { if (this.declaringClass == c || isInnerClass(this.declaringClass, c)) { ((AccessibleObject) m).setAccessible(true); } } } }
/** * Method called to check if we can use the passed method or constructor (wrt access restriction * -- public methods can be called, others usually not); and if not, if there is a work-around for * the problem. */ public static void checkAndFixAccess(Member member) { // We know all members are also accessible objects... AccessibleObject ao = (AccessibleObject) member; /* 14-Jan-2009, tatu: It seems safe and potentially beneficial to * always to make it accessible (latter because it will force * skipping checks we have no use for...), so let's always call it. */ // if (!ao.isAccessible()) { try { ao.setAccessible(true); } catch (SecurityException se) { /* 17-Apr-2009, tatu: Related to [JACKSON-101]: this can fail on * platforms like EJB and Google App Engine); so let's * only fail if we really needed it... */ if (!ao.isAccessible()) { Class<?> declClass = member.getDeclaringClass(); throw new IllegalArgumentException( "Can not access " + member + " (from class " + declClass.getName() + "; failed to set access: " + se.getMessage()); } } // } }
/** * Returns <code>true</code> if class member is public and if its declaring class is also public. */ public static boolean isPublicPublic(Member member) { if (Modifier.isPublic(member.getModifiers()) == true) { if (Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return true; } } return false; }
private String resolveTypeDiscriminatorForBackReference(Member m) { Method me = ReflectionUtils.findMethod( m.getDeclaringClass(), "get" + firstCharToUpperCase(m.getName())); if (me != null) { return resolveTypeDiscriminator(resolveReturnType(me)); } return ""; }
/** * Finds all constraint annotations defined for the given field/method and returns them in a list * of constraint descriptors. * * @param member The fields or method to check for constraints annotations. * @param type The element type the constraint/annotation is placed on. * @return A list of constraint descriptors for all constraint specified for the given field or * method. */ private List<ConstraintDescriptorImpl<?>> findConstraints(Member member, ElementType type) { assert member instanceof Field || member instanceof Method; List<ConstraintDescriptorImpl<?>> metaData = new ArrayList<ConstraintDescriptorImpl<?>>(); for (Annotation annotation : ((AnnotatedElement) member).getAnnotations()) { metaData.addAll(findConstraintAnnotations(member.getDeclaringClass(), annotation, type)); } return metaData; }
public ConstraintViolationException( String instanceToString, Iterable<Class<?>> instanceTypes, Member method, Collection<ConstraintViolation> violations) { this.instanceToString = instanceToString; this.instanceTypes = instanceTypes; mixinTypeName = method.getDeclaringClass().getName(); methodName = method.getName(); this.constraintViolations = violations; }
/** Resolve the prepared arguments stored in the given bean definition. */ private Object[] resolvePreparedArguments( String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) { Class<?>[] paramTypes = (methodOrCtor instanceof Method ? ((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes()); TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ? this.beanFactory.getCustomTypeConverter() : bw); BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter); Object[] resolvedArgs = new Object[argsToResolve.length]; for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) { Object argValue = argsToResolve[argIndex]; MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex); GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass()); if (argValue instanceof AutowiredArgumentMarker) { argValue = resolveAutowiredArgument(methodParam, beanName, null, converter); } else if (argValue instanceof BeanMetadataElement) { argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue); } else if (argValue instanceof String) { argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd); } Class<?> paramType = paramTypes[argIndex]; try { resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam); } catch (TypeMismatchException ex) { String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method"); throw new UnsatisfiedDependencyException( mbd.getResourceDescription(), beanName, argIndex, paramType, "Could not convert " + methodType + " argument value of type [" + ObjectUtils.nullSafeClassName(argValue) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage()); } } return resolvedArgs; }
protected boolean isVisible(final Class<?> baseClass, final Member element) { if (baseClass == null || element == null) return false; final int modifiers = element.getModifiers(); if (Modifier.isPublic(modifiers)) return true; if (Modifier.isProtected(modifiers)) return true; if (!Modifier.isPrivate(modifiers) && baseClass.getPackage().equals(element.getDeclaringClass().getPackage())) return true; return false; }
/** * XXX Default access superclass workaround * * <p>When a public class has a default access superclass with public members, these members are * accessible. Calling them from compiled code works fine. Unfortunately, on some JVMs, using * reflection to invoke these members seems to (wrongly) prevent access even when the modifier is * public. Calling setAccessible(true) solves the problem but will only work from sufficiently * privileged code. Better workarounds would be gratefully accepted. * * @param o the AccessibleObject to set as accessible */ static void setAccessibleWorkaround(AccessibleObject o) { if (o == null || o.isAccessible()) { return; } Member m = (Member) o; if (Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); } catch (SecurityException e) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } }
/** * XXX Default access superclass workaround. * * <p>When a {@code public} class has a default access superclass with {@code public} members, * these members are accessible. Calling them from compiled code works fine. Unfortunately, on * some JVMs, using reflection to invoke these members seems to (wrongly) prevent access even when * the modifier is {@code public}. Calling {@code setAccessible(true)} solves the problem but will * only work from sufficiently privileged code. Better workarounds would be gratefully accepted. * * @param o the AccessibleObject to set as accessible * @return a boolean indicating whether the accessibility of the object was set to true. */ static boolean setAccessibleWorkaround(final AccessibleObject o) { if (o == null || o.isAccessible()) { return false; } final Member m = (Member) o; if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); return true; } catch (final SecurityException e) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false; }
/** * Returns an array containing the available subtypes of the specified type, first looking to * subtypes listed in the annotation, then attempting to find a method using reflection. */ protected Class<?>[] getSubtypes(Class<?> type) { ArrayList<Class<?>> types = new ArrayList<Class<?>>(); // start with the null class, if allowed boolean nullable = getAnnotation().nullable(); if (nullable) { types.add(null); } // look for a subtype annotation and add its types EditorTypes ownAnnotation = getAnnotation(EditorTypes.class); EditorTypes annotation = (ownAnnotation == null) ? type.getAnnotation(EditorTypes.class) : ownAnnotation; if (annotation != null) { addSubtypes(annotation, types); } // get the config key and add the config types String key = (annotation == null) ? type.getName() : annotation.key(); if (StringUtil.isBlank(key)) { if (annotation == ownAnnotation) { Member member = getMember(); key = member.getDeclaringClass().getName() + "." + member.getName(); } else { key = type.getName(); } } Class<?>[] ctypes = _configTypes.get(key); if (ctypes != null) { Collections.addAll(types, ctypes); } // if we don't have at least one non-null class, add the type itself if (types.size() == (nullable ? 1 : 0)) { types.add(type); } // convert to array, return return types.toArray(new Class<?>[types.size()]); }
/** Returns true if the binding annotation is in the wrong place. */ private static boolean checkForMisplacedBindingAnnotations(Member member, Errors errors) { Annotation misplacedBindingAnnotation = Annotations.findBindingAnnotation( errors, member, ((AnnotatedElement) member).getAnnotations()); if (misplacedBindingAnnotation == null) { return false; } // don't warn about misplaced binding annotations on methods when there's a field with the same // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242. if (member instanceof Method) { try { if (member.getDeclaringClass().getDeclaredField(member.getName()) != null) { return false; } } catch (NoSuchFieldException ignore) { } } errors.misplacedBindingAnnotation(member, misplacedBindingAnnotation); return true; }
/** * Conveniently render an {@link AccessibleObject} accessible. * * <p>To prevent {@link SecurityException}, this is only done if the argument object and its * declaring class are non-public. * * @param accessible The object to render accessible * @return The argument object rendered accessible */ public static <T extends AccessibleObject> T accessible(T accessible) { if (accessible == null) { return null; } if (accessible instanceof Member) { Member member = (Member) accessible; if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return accessible; } } // [jOOQ #3392] The accessible flag is set to false by default, also for public members. if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; }
private void generateSetBasedDocRefView( Map<String, org.ektorp.support.DesignDocument.View> views, Member me, DocumentReferences referenceMetaData) { String fieldName = firstCharToLowerCase(me.getName()); String orderBy = referenceMetaData.orderBy(); String backRef = referenceMetaData.backReference(); if (backRef.length() == 0) { throw new ViewGenerationException( String.format( "The DocumentReferences annotation in %s must specify a backReference", me.getDeclaringClass())); } String viewName = NameConventions.backReferenceViewName(fieldName); String typeDiscriminator = resolveTypeDiscriminatorForBackReference(me); if (orderBy.length() > 0) { views.put( viewName, generateDocRefsAsSetWithOrderByView(backRef, fieldName, orderBy, typeDiscriminator)); } else { views.put(viewName, generateDocRefsAsSetView(backRef, fieldName, typeDiscriminator)); } }
/** Returns <code>true</code> if the first member is accessible from second one. */ public static boolean isAssignableFrom(Member member1, Member member2) { return member1.getDeclaringClass().isAssignableFrom(member2.getDeclaringClass()); }
/** * Checks whether the given <code>member</code> is public and non-final. These members do no need * to be set accessible using reflection. * * @param member The member to check * @return <code>true</code> if the member is public and non-final, otherwise <code>false</code>. * @see #isAccessible(java.lang.reflect.AccessibleObject) * @see #ensureAccessible(java.lang.reflect.AccessibleObject) */ public static boolean isNonFinalPublicMember(Member member) { return (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers()) && !Modifier.isFinal(member.getModifiers())); }
/* * Majority of code below from Rhino source, written by A. Sundararajan. */ @Override public Scriptable wrapAsJavaObject( Context cx, Scriptable scope, Object javaObject, Class staticType) { if (javaObject instanceof ClassLoader) { throw new SecurityException("Class loaders cannot be accessed in this environment."); } else { String name = null; if (javaObject instanceof Class) { name = ((Class) javaObject).getName(); } else if (javaObject instanceof Member) { Member member = (Member) javaObject; // Check member access. Don't allow reflective access to // non-public members. Note that we can't call checkMemberAccess // because that expects exact stack depth! if (!Modifier.isPublic(member.getModifiers())) { return null; } name = member.getDeclaringClass().getName(); } // Now, make sure that no ClassShutter prevented Class or Member // of it is accessed reflectively. Note that ClassShutter may // prevent access to a class, even though SecurityManager permit. if (name != null) { if (!classShutter.visibleToScripts(name)) { throw new SecurityException("'" + name + "' cannot be accessed in this environment."); } else { return new NativeJavaObject(scope, javaObject, staticType); } } } // we have got some non-reflective object. Class dynamicType = javaObject.getClass(); String name = dynamicType.getName(); if (!classShutter.visibleToScripts(name)) { // Object of some sensitive class (such as sun.net.www.* // objects returned from public method of java.net.URL class. // We expose this object as though it is an object of some // super class that is safe for access. Class type = null; // Whenever a Java Object is wrapped, we are passed with a // staticType which is the type found from environment. For // example, method return type known from signature. The dynamic // type would be the actual Class of the actual returned object. // If the staticType is an interface, we just use that type. if (staticType != null && staticType.isInterface()) { type = staticType; } else { // dynamicType is always a class type and never an interface. // find an accessible super class of the dynamic type. while (true) { dynamicType = dynamicType.getSuperclass(); if (dynamicType != null) { name = dynamicType.getName(); if (classShutter.visibleToScripts(name)) { type = dynamicType; break; } } else { break; } } // atleast java.lang.Object has to be accessible. So, when // we reach here, type variable should not be null. assert type != null : "even java.lang.Object is not accessible?"; } // create custom wrapper with the 'safe' type. return new JavascriptJavaObject(scope, javaObject, type); } else { return new NativeJavaObject(scope, javaObject, staticType); } }
public String determineMemberDescription(Member member) { return member.getDeclaringClass().getName() + '#' + member.getName(); }