下面列出了java.lang.reflect.Modifier#PROTECTED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Returns an {@link Invokable} for each public methods or constructors of a type. */
private Set<Invokable> getExposedInvokables(TypeToken<?> type) {
Set<Invokable> invokables = Sets.newHashSet();
for (Constructor constructor : type.getRawType().getConstructors()) {
if (0 != (constructor.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED))) {
invokables.add(type.constructor(constructor));
}
}
for (Method method : type.getRawType().getMethods()) {
if (0 != (method.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED))) {
invokables.add(type.method(method));
}
}
return invokables;
}
/**
* Returns subclass-accessible no-arg constructor of first non-serializable
* superclass, or null if none found. Access checks are disabled on the
* returned constructor (if any).
*/
private static Constructor<?> getSerializableConstructor(Class<?> cl) {
Class<?> initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
Class<?> prev = initCl;
if ((initCl = initCl.getSuperclass()) == null ||
(!disableSerialConstructorChecks && !superHasAccessibleConstructor(prev))) {
return null;
}
}
try {
Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null);
int mods = cons.getModifiers();
if ((mods & Modifier.PRIVATE) != 0 ||
((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
!packageEquals(cl, initCl)))
{
return null;
}
cons = reflFactory.newConstructorForSerialization(cl, cons);
cons.setAccessible(true);
return cons;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Declares a field.
*
* @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
* Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
* {@link Modifier#FINAL}, {@link Modifier#VOLATILE}, and {@link
* Modifier#TRANSIENT}.
* @param staticValue a constant representing the initial value for the
* static field, possibly null. This must be null if this field is
* non-static.
*/
public void declare(FieldId<?, ?> fieldId, int flags, Object staticValue) {
TypeDeclaration typeDeclaration = getTypeDeclaration(fieldId.declaringType);
if (typeDeclaration.fields.containsKey(fieldId)) {
throw new IllegalStateException("already declared: " + fieldId);
}
int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED
| Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT
| AccessFlags.ACC_SYNTHETIC;
if ((flags & ~supportedFlags) != 0) {
throw new IllegalArgumentException("Unexpected flag: "
+ Integer.toHexString(flags));
}
if ((flags & Modifier.STATIC) == 0 && staticValue != null) {
throw new IllegalArgumentException("staticValue is non-null, but field is not static");
}
FieldDeclaration fieldDeclaration = new FieldDeclaration(fieldId, flags, staticValue);
typeDeclaration.fields.put(fieldId, fieldDeclaration);
}
/**
* Create a sub-method from this method to allow the code builder to split a
* single logical method into multiple methods to avoid the 64k per-method
* code size limit. The sub method with inherit the thrown exceptions of
* this method.
*
* @param returnType
* Return type of the new method
* @param withParameters
* True to define the method with matching parameters false to
* define it with no parameters.
* @return A valid empty sub method.
*/
final BCMethod getNewSubMethod(String returnType, boolean withParameters) {
int modifiers = myEntry.getModifier();
// the sub-method can be private to ensure that no-one
// can call it accidentally from outside the class.
modifiers &= ~(Modifier.PROTECTED | Modifier.PUBLIC);
modifiers |= Modifier.PRIVATE;
String subMethodName = myName + "_s"
+ Integer.toString(subMethodCount++);
BCMethod subMethod = (BCMethod) cb.newMethodBuilder(modifiers,
returnType, subMethodName, withParameters ? parameterTypes
: null);
subMethod.thrownExceptions = this.thrownExceptions;
return subMethod;
}
/**
* Returns subclass-accessible no-arg constructor of first non-serializable
* superclass, or null if none found. Access checks are disabled on the
* returned constructor (if any).
*/
private static Constructor<?> getSerializableConstructor(Class<?> cl) {
Class<?> initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
Class<?> prev = initCl;
if ((initCl = initCl.getSuperclass()) == null ||
(!disableSerialConstructorChecks && !superHasAccessibleConstructor(prev))) {
return null;
}
}
try {
Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null);
int mods = cons.getModifiers();
if ((mods & Modifier.PRIVATE) != 0 ||
((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
!packageEquals(cl, initCl)))
{
return null;
}
cons = reflFactory.newConstructorForSerialization(cl, cons);
cons.setAccessible(true);
return cons;
} catch (NoSuchMethodException ex) {
return null;
}
}
private static int addPublicModifier(int mod)
{
mod &= ~ (Modifier.PRIVATE);
mod &= ~ (Modifier.PROTECTED);
mod |= (Modifier.PUBLIC);
return mod;
}
@Test
public void mapsSimpleAnnotatedConstructorWithParams() throws ClassNotFoundException {
javaSourceCode("test.Foo", //
"package test;", //
"public class Foo {",//
"@Deprecated protected Foo(String a) {}", //
"}" //
);
setTargetAnnotations(new String[] {"java.lang.Deprecated"});
assertJavaSourceCompileWithoutError();
final Set<Class> annotatedClasses = getProcessedClasses();
assertThat(annotatedClasses.contains(Class.forNameSafe("test.Foo")), is(true));
final Class expectedParamType = Class.forName("java.lang.String");
final Class aClass = Class.forName("test.Foo");
assertThat(aClass.getConstructors().size(), is(1));
final Constructor constructor = (Constructor) aClass.getConstructors().get(0);
final Constructor expected = new Constructor(aClass, new Class[] {expectedParamType}, new Class[0], Modifier.PROTECTED);
assertThat(constructor, is(expected));
assertThat(constructor.getModifiers(), is(Modifier.PROTECTED));
final java.lang.annotation.Annotation[] annotations = constructor.getAnnotations();
assertThat(annotations.length, is(1));
final Class deprecatedAnnotationClass = Class.forName("java.lang.Deprecated");
assertThat(((Annotation) annotations[0]).rnrAnnotationType(), is(deprecatedAnnotationClass));
assertThat(((Annotation)constructor.getAnnotation(deprecatedAnnotationClass)).rnrAnnotationType(), is(deprecatedAnnotationClass));
final Class<?>[] paramTypes = constructor.getParameterTypes();
assertThat(paramTypes.length, is(1));
assertThat(paramTypes[0], is(expectedParamType));
assertThat(((Annotation)constructor.getAnnotation(deprecatedAnnotationClass)).rnrAnnotationType(), is(deprecatedAnnotationClass));
}
/**
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* null if no match found. Access checks are disabled on the returned
* method (if any).
*/
private static Method getInheritableMethod(Class<?> cl, String name,
Class<?>[] argTypes,
Class<?> returnType)
{
Method meth = null;
Class<?> defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return null;
}
meth.setAccessible(true);
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return null;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return meth;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl) ? meth : null;
} else {
return packageEquals(cl, defCl) ? meth : null;
}
}
public static void main(String[] args) throws Exception {
/* We are not testing for the ACC_SUPER bug, so strip we strip
* synchorized. */
int m = 0;
m = Inner.class.getModifiers() & (~Modifier.SYNCHRONIZED);
if (m != Modifier.PRIVATE)
throw new Exception("Access bits for innerclass not from " +
"InnerClasses attribute");
m = Protected.class.getModifiers() & (~Modifier.SYNCHRONIZED);
if (m != Modifier.PROTECTED)
throw new Exception("Protected inner class wronged modifiers");
}
/**
* Convert modifier bits from private coding used by
* the compiler to that of java.lang.reflect.Modifier.
*/
static int translateModifiers(long flags) {
int result = 0;
if ((flags & Flags.ABSTRACT) != 0)
result |= Modifier.ABSTRACT;
if ((flags & Flags.FINAL) != 0)
result |= Modifier.FINAL;
if ((flags & Flags.INTERFACE) != 0)
result |= Modifier.INTERFACE;
if ((flags & Flags.NATIVE) != 0)
result |= Modifier.NATIVE;
if ((flags & Flags.PRIVATE) != 0)
result |= Modifier.PRIVATE;
if ((flags & Flags.PROTECTED) != 0)
result |= Modifier.PROTECTED;
if ((flags & Flags.PUBLIC) != 0)
result |= Modifier.PUBLIC;
if ((flags & Flags.STATIC) != 0)
result |= Modifier.STATIC;
if ((flags & Flags.SYNCHRONIZED) != 0)
result |= Modifier.SYNCHRONIZED;
if ((flags & Flags.TRANSIENT) != 0)
result |= Modifier.TRANSIENT;
if ((flags & Flags.VOLATILE) != 0)
result |= Modifier.VOLATILE;
return result;
}
/**
* Convert modifier bits from private coding used by
* the compiler to that of java.lang.reflect.Modifier.
*/
static int translateModifiers(long flags) {
int result = 0;
if ((flags & Flags.ABSTRACT) != 0)
result |= Modifier.ABSTRACT;
if ((flags & Flags.FINAL) != 0)
result |= Modifier.FINAL;
if ((flags & Flags.INTERFACE) != 0)
result |= Modifier.INTERFACE;
if ((flags & Flags.NATIVE) != 0)
result |= Modifier.NATIVE;
if ((flags & Flags.PRIVATE) != 0)
result |= Modifier.PRIVATE;
if ((flags & Flags.PROTECTED) != 0)
result |= Modifier.PROTECTED;
if ((flags & Flags.PUBLIC) != 0)
result |= Modifier.PUBLIC;
if ((flags & Flags.STATIC) != 0)
result |= Modifier.STATIC;
if ((flags & Flags.SYNCHRONIZED) != 0)
result |= Modifier.SYNCHRONIZED;
if ((flags & Flags.TRANSIENT) != 0)
result |= Modifier.TRANSIENT;
if ((flags & Flags.VOLATILE) != 0)
result |= Modifier.VOLATILE;
return result;
}
/**
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* null if no match found. Access checks are disabled on the returned
* method (if any).
*/
private static Method getInheritableMethod(Class<?> cl, String name,
Class<?>[] argTypes,
Class<?> returnType)
{
Method meth = null;
Class<?> defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return null;
}
meth.setAccessible(true);
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return null;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return meth;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl) ? meth : null;
} else {
return packageEquals(cl, defCl) ? meth : null;
}
}
/**
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* null if no match found. Access checks are disabled on the returned
* method (if any).
*/
private static Method getInheritableMethod(Class<?> cl, String name,
Class<?>[] argTypes,
Class<?> returnType)
{
Method meth = null;
Class<?> defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return null;
}
meth.setAccessible(true);
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return null;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return meth;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl) ? meth : null;
} else {
return packageEquals(cl, defCl) ? meth : null;
}
}
/**
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* null if no match found. Access checks are disabled on the returned
* method (if any).
*/
private static Method getInheritableMethod(Class<?> cl, String name,
Class<?>[] argTypes,
Class<?> returnType)
{
Method meth = null;
Class<?> defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return null;
}
meth.setAccessible(true);
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return null;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return meth;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl) ? meth : null;
} else {
return packageEquals(cl, defCl) ? meth : null;
}
}
@Override
public int getModifiers() {
if (isArray()) {
return (getElementalType().getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED)) | Modifier.FINAL | Modifier.ABSTRACT;
} else {
return getAccessFlags() & jvmClassModifiers();
}
}
@Test
public void mapsSimpleAnnotatedMethod() throws ClassNotFoundException {
javaSourceCode("test.Foo", //
"package test;", //
"public class Foo {",//
"@Deprecated protected String s() {return \"foo\"; }", //
"}" //
);
setTargetAnnotations(new String[] {"java.lang.Deprecated"});
assertJavaSourceCompileWithoutError();
final Set<Class> annotatedClasses = getProcessedClasses();
assertThat(annotatedClasses.contains(Class.forNameSafe("test.Foo")), is(true));
final Class aClass = Class.forName("test.Foo");
assertThat(aClass.getMethods().size(), is(1));
final Method method = (Method) aClass.getMethods().get(0);
final Method expected = new Method(aClass, "s", new Class[0], Class.forNameSafe("java.lang.String"), new Class[0], Modifier.PROTECTED);
assertThat(method, is(expected));
assertThat(method.getModifiers(), is(Modifier.PROTECTED));
final java.lang.annotation.Annotation[] annotations = method.getAnnotations();
assertThat(annotations.length, is(1));
final Class deprecatedAnnotationClass = Class.forName("java.lang.Deprecated");
assertThat(((Annotation) annotations[0]).rnrAnnotationType(), is(deprecatedAnnotationClass));
assertThat(((Annotation)method.getAnnotation(deprecatedAnnotationClass)).rnrAnnotationType(), is(deprecatedAnnotationClass));
}
/**
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* null if no match found. Access checks are disabled on the returned
* method (if any).
*/
private static Method getInheritableMethod(Class<?> cl, String name,
Class<?>[] argTypes,
Class<?> returnType)
{
Method meth = null;
Class<?> defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return null;
}
meth.setAccessible(true);
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return null;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return meth;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl) ? meth : null;
} else {
return packageEquals(cl, defCl) ? meth : null;
}
}
private void generateConstructors() throws AdaptationException {
boolean gotCtor = false;
for (final Constructor<?> ctor: superClass.getDeclaredConstructors()) {
final int modifier = ctor.getModifiers();
if((modifier & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0 && !isCallerSensitive(ctor)) {
generateConstructors(ctor);
gotCtor = true;
}
}
if(!gotCtor) {
throw new AdaptationException(ERROR_NO_ACCESSIBLE_CONSTRUCTOR, superClass.getCanonicalName());
}
}
/**
* Returns true if a non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
* false if no match found.
*/
private static boolean getInheritableMethod(Class cl, String name,
Class[] argTypes,
Class returnType)
{
Method meth = null;
Class defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
break;
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
if ((meth == null) || (meth.getReturnType() != returnType)) {
return false;
}
int mods = meth.getModifiers();
if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
return false;
} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
return true;
} else if ((mods & Modifier.PRIVATE) != 0) {
return (cl == defCl);
} else {
return packageEquals(cl, defCl);
}
}
public static Class<?> generateAnonymousClassSubstitute(String newOuterClass, ClassNode paramNode, ClassLoader targetClassLoader) {
ClassNode node = new ClassNode(Opcodes.ASM5);
paramNode.accept(node);
String originalClassName = node.name;
String originalContainingClass = node.name.substring(0, node.name.lastIndexOf('$'));
node.name = classPrefix + classCounter.getAndIncrement();
node.access = Modifier.PUBLIC;
List<MethodNode> methods = (List<MethodNode>) node.methods;
for (MethodNode method : methods) {
method.access = (method.access | Modifier.PUBLIC) & ~(Modifier.PRIVATE | Modifier.PROTECTED);
for (ListIterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext(); ) {
AbstractInsnNode instruction = iter.next();
if (instruction instanceof FieldInsnNode) {
FieldInsnNode fieldInsn = (FieldInsnNode) instruction;
if ("<init>".equals(method.name)) {
fieldInsn.owner = node.name;
if (fieldInsn.desc.equals("L" + originalContainingClass + ";"))
fieldInsn.desc = "L" + newOuterClass + ";";
continue;
}
if (fieldInsn.owner.equals(originalClassName))
fieldInsn.owner = node.name;
}
if (instruction instanceof MethodInsnNode) {
MethodInsnNode methodInsn = (MethodInsnNode) instruction;
if (methodInsn.owner.equals(originalClassName))
methodInsn.owner = node.name;
else if (methodInsn.owner.equals(originalContainingClass))
methodInsn.owner = newOuterClass;
}
}
if (method.name.equals("<init>"))
method.desc = method.desc.replace(originalContainingClass, newOuterClass);
}
List<FieldNode> fields = (List<FieldNode>) node.fields;
for (FieldNode field : fields) {
field.access = (field.access | Modifier.PUBLIC) & ~(Modifier.PRIVATE | Modifier.PROTECTED);
if (!field.desc.equals("L" + originalContainingClass + ";"))
continue;
field.desc = "L" + newOuterClass + ";";
}
node.outerClass = null;
ClassWriter writer = new ClassWriter(Opcodes.ASM5);
node.accept(writer);
byte[] data = writer.toByteArray();
try {
return (Class<?>) classLoaderDefineClass.invoke(targetClassLoader, node.name.replace('/', '.'), data, 0, data.length);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}