问题
Using Java Reflection, you can detect all methods and their returns type. But is there a way to detect if a method is declared as native or not?
回答1:
Yes you can.The method getModifiers() returns an int which applied the right mask can tell you if the method is native or not
I would suggest doing it like this, for convenience:
int modifiers = myMethod.getModifiers();
boolean isNative = Modifier.isNative(modifiers);
The Modifier class is an utility specialized class meant to apply the appropriate masks in order to discover the modifiers of the method.
回答2:
Method has a getModifiers() method which returns the modifiers as an int, and one of the modifiers is Modifier.NATIVE, which is what your looking for. Modifier.isNative() can be used to decode the argument from getModifiers().
(Basically, if you have your method as a Method object named m, then Modifier.isNative(m.getModifiers()) should do it.)
回答3:
You can check the modifiers associated with the method. The example below prints all the native methods of Object:
for (Method m : methods) {
int mod = m.getModifiers();
if ((mod & Modifier.NATIVE) != 0) {
System.out.println(m.getName());
}
}
EDIT
This other answer gives a better approach that avoids the bitwise matching part.
回答4:
Yes you can, just check the modifiers of the method:
public class NativeMethodModifierTest
{
public class NativeMethodTest
{
public native void method();
}
@Test
public void testNativeMember()
{
Method m = NativeMethodTest.class.getMethods()[0];
Assert.assertEquals(Modifier.NATIVE, (m.getModifiers() & Modifier.NATIVE));
}
}
回答5:
Use getModifiers(), you can read the flags using the utility functions in Modifier:
Methods meth = Object.class.getDeclaredMethods()[0];
int mod = meth.getModifiers();
boolean native = Modifier.isNative(mod);
来源:https://stackoverflow.com/questions/11869598/using-java-reflection-can-you-detect-if-a-method-is-native-or-not