// ----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = NullConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); }
private static String getTypeMetadata(Class<?> clazz) { StringBuilder sb = new StringBuilder(); if (clazz.isInterface()) { sb.append("I "); } else { sb.append("C "); } if (Modifier.isStatic(clazz.getModifiers())) { sb.append("S\n"); } else { sb.append("I\n"); } Class<?> baseClass = clazz.getSuperclass(); sb.append("B " + ((baseClass != null) ? baseClass.getName() : "").replace('.', '/') + "\n"); Method[] methods = clazz.getDeclaredMethods(); Arrays.sort(methods, methodComparator); for (Method m : methods) { int modifiers = m.getModifiers(); if (!Modifier.isStatic(modifiers) && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) { sb.append("M "); sb.append(m.getName()); Class<?>[] params = m.getParameterTypes(); String sig = MethodResolver.getMethodSignature(m.getReturnType(), params); sb.append(" "); sb.append(sig); int paramCount = params.length; sb.append(" "); sb.append(paramCount); sb.append("\n"); } } Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { int modifiers = f.getModifiers(); if (!Modifier.isStatic(modifiers) && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) { sb.append("F "); sb.append(f.getName()); sb.append(" "); String sig = MethodResolver.getTypeSignature(f.getType()); sb.append(sig); sb.append(" 0\n"); } } String ret = sb.toString(); return ret; }
public FieldDefinition(Field field) { this.name = field.getName(); this.type = field.getType().getName(); this.isStatic = Modifier.isStatic(field.getModifiers()); this.isPublic = !Modifier.isPrivate(field.getModifiers()) && !Modifier.isProtected(field.getModifiers()); }
private boolean printIfProtected(int mod) { boolean present = Modifier.isProtected(mod); if (present) { writer.print("protected "); } return present; }
/** * Checks for final methods on the given {@code Class}, as well as package-visible methods across * ClassLoaders, and writes warnings to the log for each one found. */ private void doValidateClass(Class<?> proxySuperClass, ClassLoader proxyClassLoader) { if (Object.class != proxySuperClass) { Method[] methods = proxySuperClass.getDeclaredMethods(); for (Method method : methods) { int mod = method.getModifiers(); if (!Modifier.isStatic(mod)) { if (Modifier.isFinal(mod)) { logger.info( "Unable to proxy method [" + method + "] because it is final: " + "All calls to this method via a proxy will NOT be routed to the target instance."); } else if (!Modifier.isPublic(mod) && !Modifier.isProtected(mod) && !Modifier.isPrivate(mod) && proxyClassLoader != null && proxySuperClass.getClassLoader() != proxyClassLoader) { logger.info( "Unable to proxy method [" + method + "] because it is package-visible " + "across different ClassLoaders: All calls to this method via a proxy will " + "NOT be routed to the target instance."); } } } doValidateClass(proxySuperClass.getSuperclass(), proxyClassLoader); } }
AtomicReferenceFieldUpdaterImpl( Class<T> tclass, Class<V> vclass, String fieldName, Class<?> caller) { Field field = null; Class fieldClass = null; int modifiers = 0; try { field = tclass.getDeclaredField(fieldName); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess(caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); fieldClass = field.getType(); } catch (Exception ex) { throw new RuntimeException(ex); } if (vclass != fieldClass) throw new ClassCastException(); if (vclass.isPrimitive()) throw new IllegalArgumentException("Must be reference type"); if (!Modifier.isVolatile(modifiers)) throw new IllegalArgumentException("Must be volatile type"); this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null; this.tclass = tclass; if (vclass == Object.class) this.vclass = null; else this.vclass = vclass; offset = unsafe.objectFieldOffset(field); }
/** 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); } } } }
static Method[] getOverridableMethods(Class c) { ArrayList<Method> list = new ArrayList<Method>(); HashSet<String> skip = new HashSet<String>(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } c = c.getSuperclass(); } return list.toArray(new Method[list.size()]); }
@Test public void checkThatConstructorIsProtected() { for (Constructor<?> constr : Earth.class.getDeclaredConstructors()) { assertTrue( "Constructors should be protected to allow subclasses of singleton", Modifier.isProtected(constr.getModifiers())); } }
/** java.lang.reflect.InvocationTargetException#InvocationTargetException() */ public void test_Constructor() throws Exception { Constructor<InvocationTargetException> ctor = InvocationTargetException.class.getDeclaredConstructor(); assertNotNull("Parameterless constructor does not exist.", ctor); assertTrue("Constructor is not protected", Modifier.isProtected(ctor.getModifiers())); // create an instance of a subtype using this constructor SubInvocationTargetException subException = new SubInvocationTargetException(); }
/** * Locates the entity manager field that should be used. * * <p>If a parent is defined, it must provide the field. * * <p>We generally expect the field to be named "entityManager" and be of type * javax.persistence.EntityManager. We also require it to be public or protected, and annotated * with @PersistenceContext. If there is an existing field which doesn't meet these latter * requirements, we add an underscore prefix to the "entityManager" name and try again, until such * time as we come up with a unique name that either meets the requirements or the name is not * used and we will create it. * * @return the entity manager field (never returns null) */ public FieldMetadata getEntityManagerField() { if (parent != null) { // The parent is required to guarantee this is available return parent.getEntityManagerField(); } // Need to locate it ourself int index = -1; while (true) { // Compute the required field name index++; final JavaSymbolName fieldSymbolName = new JavaSymbolName(StringUtils.repeat("_", index) + "entityManager"); final FieldMetadata candidate = governorTypeDetails.getField(fieldSymbolName); if (candidate != null) { // Verify if candidate is suitable if (!Modifier.isPublic(candidate.getModifier()) && !Modifier.isProtected(candidate.getModifier()) && (Modifier.TRANSIENT != candidate.getModifier())) { // Candidate is not public and not protected and not simply a transient field (in which // case subclasses // will see the inherited field), so any subsequent subclasses won't be able to see it. // Give up! continue; } if (!candidate.getFieldType().equals(ENTITY_MANAGER)) { // Candidate isn't an EntityManager, so give up continue; } if (MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), PERSISTENCE_CONTEXT) == null) { // Candidate doesn't have a PersistenceContext annotation, so give up continue; } // If we got this far, we found a valid candidate return candidate; } // Candidate not found, so let's create one final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); final AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(PERSISTENCE_CONTEXT); if (StringUtils.hasText(crudAnnotationValues.getPersistenceUnit())) { annotationBuilder.addStringAttribute("unitName", crudAnnotationValues.getPersistenceUnit()); } annotations.add(annotationBuilder); final FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder( getId(), Modifier.TRANSIENT, annotations, fieldSymbolName, ENTITY_MANAGER); return fieldBuilder.build(); } }
/** * Getter for visibility. * * @return String representing the visibility. */ public String getVisibility() { String v = "public"; if (Modifier.isProtected(this.modifier)) { v = "protected"; } else if (Modifier.isPrivate(this.modifier)) { v = "private"; } return v; }
private static String stringVisibility(int modifiers) { if (Modifier.isProtected(modifiers)) { return "protected"; } else if (Modifier.isPublic(modifiers)) { return "public"; } else { return ""; } }
/** * Returns the visibility of the method as a character private: - public: + protected: # package: * ~ */ private char getVisibilityCharacter(Method method) { // private if (Modifier.isPrivate(method.getModifiers())) return '-'; // protected if (Modifier.isProtected(method.getModifiers())) return '#'; // public if (Modifier.isPublic(method.getModifiers())) return '+'; // package return '~'; }
// 只有 public static boolean isAvailableModifier(Class<?> realClazz, Class<?> superClazz, Field field) { int modifier = field.getModifiers(); // 不能是final的也不能是static的, if (realClazz == superClazz) { return !Modifier.isStatic(modifier) && !Modifier.isFinal(modifier); } else { // 如果是父类的话还必须是public或者protect的范围 return !Modifier.isFinal(modifier) && !Modifier.isFinal(modifier) && (Modifier.isPublic(modifier) || Modifier.isProtected(modifier)); } }
public String toDetailedString() { Object bean = component; if (bean == null) { return "<null>"; } TreeSet<String> treeSet = new TreeSet<String>(); Class clazz = bean.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { StringBuilder str = new StringBuilder(); int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers)) { str.append('+'); } else if (Modifier.isProtected(modifiers)) { str.append('#'); } else if (Modifier.isPrivate(modifiers)) { str.append('-'); } else { str.append(' '); } str.append(field.getName()).append(':'); try { Object value = field.get(bean); if (value == null) { str.append("<null>"); } else { String valueString = value.toString(); if (valueString.length() > 250) { valueString = valueString.substring(0, 250) + "..."; } str.append(valueString); } } catch (IllegalAccessException ignore) { str.append("N/A"); } str.append('\n'); treeSet.add(htmlSafe(str.toString())); } StringBuilder resolve = new StringBuilder("<html>"); for (String s1 : treeSet) { resolve.append(s1); } return resolve.toString(); }
private String GetVisibility(int modifiers) { if (Modifier.isPrivate(modifiers)) { return StaticStrings.Private; } if (Modifier.isProtected(modifiers)) { return StaticStrings.Protected; } if (Modifier.isPublic(modifiers)) { return StaticStrings.Public; } return StaticStrings.Package; }
public class MethodUtility extends ObjectUtility<Method> { public static final Predicate<Method> IS_PUBLIC_METHOD = o -> Modifier.isPublic(o.getModifiers()); public static final Predicate<Method> IS_PRIVATE_METHOD = o -> Modifier.isPrivate(o.getModifiers()); public static final Predicate<Method> IS_PROTECTED_METHOD = o -> Modifier.isProtected(o.getModifiers()); public static final Predicate<Method> IS_GETTER = o -> o.getParameterCount() == 0 && o.getName().startsWith("get"); public static final Predicate<Method> IS_SETTER = o -> o.getParameterCount() == 1 && o.getName().startsWith("set"); private final Object parent; public MethodUtility(Method object, Object parent) { super(object); this.parent = parent; } /** @see Method#toString() */ @Override public String toString() { return map(Method::toString).orElse(null); } /** * @see Method#invoke(Object, Object...) * @throws IllegalAccessException This checked exception is thrown by the {@link Rethrower}. * @throws IllegalArgumentException * @throws InvocationTargetException This checked exception is thrown by the {@link Rethrower}. */ @SuppressWarnings({"JavaDoc", "unchecked"}) public <T> T invoke(Object... arguments) { return wrap(o -> (T) o.invoke(parent, arguments)); } public void makeAccessible() { ifPresent( method -> $(method) .filter( m -> !Modifier.isPublic(m.getModifiers()) || !Modifier.isPublic(m.getDeclaringClass().getModifiers())) .filter(m -> !m.isAccessible()) .ifPresent(m -> m.setAccessible(true))); } private <T> T wrap(CheckedFunction<Method, T> function) { makeAccessible(); return map(o -> Rethrower.rethrow(function, o)).orElse(null); } }
public static Visibility buildVisibility(int javaSpecModifiers) { if (Modifier.isPublic(javaSpecModifiers)) { return Visibility.PUBLIC; } if (Modifier.isProtected(javaSpecModifiers)) { return Visibility.PROTECTED; } if (Modifier.isPrivate(javaSpecModifiers)) { return Visibility.PRIVATE; } return Visibility.PACKAGE_PRIVATE; }
/** * Returns true if a overrides b. Assumes signatures of a and b are the same and a's declaring * class is a subclass of b's declaring class. */ private static boolean overrides(Method a, Method b) { // See JLS section 8.4.8.1 int modifiers = b.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) { return true; } if (Modifier.isPrivate(modifiers)) { return false; } // b must be package-private return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage()); }
boolean isWithin(int modifiers, String scope) { boolean pub = Modifier.isPublic(modifiers); boolean pri = Modifier.isPrivate(modifiers); boolean pro = Modifier.isProtected(modifiers); boolean def = !pub & !pri & !pro; if (PUBLIC.equals(scope)) return pub; else if (PROTECTED.equals(scope)) return pub || pro; else if (DEFAULT.equals(scope)) return def || pub || pro; else // private return true; }
/** * Returns array of all methods that are accessible from given class, upto limit (usually <code> * Object.class</code>). Abstract methods are ignored. */ public static Method[] getAccessibleMethods(Class clazz, Class limit) { Package topPackage = clazz.getPackage(); List<Method> methodList = new ArrayList<Method>(); int topPackageHash = topPackage == null ? 0 : topPackage.hashCode(); boolean top = true; do { if (clazz == null) { break; } Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method method : declaredMethods) { if (Modifier.isVolatile(method.getModifiers())) { continue; } // if (Modifier.isAbstract(method.getModifiers())) { // continue; // } if (top == true) { // add all top declared methods methodList.add(method); continue; } int modifier = method.getModifiers(); if (Modifier.isPrivate(modifier) == true) { continue; // ignore super private methods } if (Modifier.isAbstract(modifier) == true) { // ignore super abstract methods continue; } if (Modifier.isPublic(modifier) == true) { addMethodIfNotExist(methodList, method); // add super public methods continue; } if (Modifier.isProtected(modifier) == true) { addMethodIfNotExist(methodList, method); // add super protected methods continue; } // add super default methods from the same package Package pckg = method.getDeclaringClass().getPackage(); int pckgHash = pckg == null ? 0 : pckg.hashCode(); if (pckgHash == topPackageHash) { addMethodIfNotExist(methodList, method); } } top = false; } while ((clazz = clazz.getSuperclass()) != limit); Method[] methods = new Method[methodList.size()]; for (int i = 0; i < methods.length; i++) { methods[i] = methodList.get(i); } return methods; }
static Method[] getOverridableMethods(Class c) { ArrayList list = new ArrayList(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) continue; if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) list.add(methods[i]); } c = c.getSuperclass(); } return (Method[]) list.toArray(new Method[list.size()]); }
private static Protection getProtection(int modifiers) { Protection protection; if (Modifier.isPublic(modifiers)) { protection = PUBLIC; } else if (Modifier.isPrivate(modifiers)) { protection = PRIVATE; } else if (Modifier.isProtected(modifiers)) { protection = PROTECTED; } else { protection = DEFAULT; } return protection; }
/** * Returns true if the entity is accessible to the specified level of protection. * * @param modifiers the modifiers as returned by Member.getModifiers() or Class.getModifiers() * @param level the level of protection * @return if the Member is accessible to the specified level of protection. * @see Member.getModifiers() * @see Class.getModifiers() */ private static boolean isAccessible(int modifiers, int level) { switch (level) { case PUBLIC: // member is accessible if it has public access return Modifier.isPublic(modifiers); case PROTECTED: // accessible if member is protected return Modifier.isProtected(modifiers); case DEFAULT: // accessible if member is not public, protected // or private return (!Modifier.isPublic(modifiers) && !Modifier.isProtected(modifiers) && !Modifier.isPrivate(modifiers)); case PRIVATE: // accessible if member is private return Modifier.isPrivate(modifiers); default: // cannot get here any more, since the access level is // only used internally throw new Error( "Completion.isAccessible(int, int) " + "called with incorrect access level parameter:" + level); } // switch }
private static List<Method> getInheritedMethods(Class baseClass, List<Method> methods) { Collections.addAll(methods, baseClass.getMethods()); Class currentClass = baseClass; while (currentClass != null) { Method[] protectedMethods = currentClass.getDeclaredMethods(); for (Method method : protectedMethods) { if (method.getName().indexOf('$') != -1) continue; if (Modifier.isProtected(method.getModifiers()) && !containsEquivalentMethod(methods, method)) methods.add(method); } currentClass = currentClass.getSuperclass(); } return methods; }
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; }
/** * Gets the visibility modifiers for the property as defined by the getter and setter methods. * * @return the visibility modifier of the getter, the setter, or both depending on which exist */ public int getModifiers() { MetaMethod getter = getGetter(); MetaMethod setter = getSetter(); if (setter != null && getter == null) return setter.getModifiers(); if (getter != null && setter == null) return getter.getModifiers(); int modifiers = getter.getModifiers() | setter.getModifiers(); int visibility = 0; if (Modifier.isPublic(modifiers)) visibility = Modifier.PUBLIC; if (Modifier.isProtected(modifiers)) visibility = Modifier.PROTECTED; if (Modifier.isPrivate(modifiers)) visibility = Modifier.PRIVATE; int states = getter.getModifiers() & setter.getModifiers(); states &= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE); states |= visibility; return states; }
/** setModifiers - set the attribute values related to modifiers here */ protected void setModifiers() { Field javaFieldTarget = (Field) getTarget(); // For JDK reflection, I don't think we can set the initializer int modifiers = getSourceField().getModifiers(); javaFieldTarget.setStatic(java.lang.reflect.Modifier.isStatic(modifiers)); javaFieldTarget.setTransient(java.lang.reflect.Modifier.isTransient(modifiers)); javaFieldTarget.setVolatile(java.lang.reflect.Modifier.isVolatile(modifiers)); javaFieldTarget.setFinal(java.lang.reflect.Modifier.isFinal(modifiers)); // Set visibility if (java.lang.reflect.Modifier.isPublic(modifiers)) javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PUBLIC_LITERAL); else if (java.lang.reflect.Modifier.isPrivate(modifiers)) javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PRIVATE_LITERAL); else if (java.lang.reflect.Modifier.isProtected(modifiers)) javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PROTECTED_LITERAL); else javaFieldTarget.setJavaVisibility(JavaVisibilityKind.PACKAGE_LITERAL); }
public boolean isVisible(Member m) { switch (this) { case ANY: return true; case NONE: return false; case NON_PRIVATE: return !Modifier.isPrivate(m.getModifiers()); case PROTECTED_AND_PUBLIC: if (Modifier.isProtected(m.getModifiers())) { return true; } // fall through to public case: case PUBLIC_ONLY: return Modifier.isPublic(m.getModifiers()); } return false; }