Using Java Reflection, can you determine if a method is native or not?

Using Java Reflection, you can detect all methods and their return type. But is there a way to determine if a method is declared as native or not?

+4
java reflection native
Aug 08 2018-12-18T00:
source share
5 answers

Yes, you can. The getModifiers() method returns an int that applied the correct mask, can tell you whether 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 a specialized utility class designed to use appropriate masks to detect method modifiers.

+11
Aug 08 2018-12-12T00:
source share

You can check the modifiers associated with this method. The following example prints all of the built-in Object methods:

 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 to avoid the bitwise part.

+5
Aug 08 2018-12-12T00:
source share

The method has a getModifiers() method that returns modifiers as int, and one of the modifiers is Modifier.NATIVE , and this is what you are looking for. Modifier.isNative() can be used to decode the argument from getModifiers() .

(Basically, if you have a method as a Method object named m , then Modifier.isNative(m.getModifiers()) should do this.)

+5
Aug 08 '12 at 17:11
source share

Yes, you can just check the method modifiers:

 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)); } } 
+3
Aug 08 '12 at 17:13
source share

Use getModifiers() , you can read flags using utility functions in Modifier :

 Methods meth = Object.class.getDeclaredMethods()[0]; int mod = meth.getModifiers(); boolean native = Modifier.isNative(mod); 
+3
Aug 08 '12 at 17:13
source share



All Articles