Using Java Reflection, can you detect if a method is Native or not?

百般思念 提交于 2019-12-21 17:49:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!