B4J Question java reflection parameters of a method

wl

Well-Known Member
Licensed User
Longtime User
Hello,

I have some inline java to do some reflection on classes. I'm aware of agrahams library but it seems to be missing the possibility to get the parameter types of a method.

It seems this should be supported in java 8, but when trying to compile I get:

B4X:
Note: src\b4j\example\main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

On stackoverflow I found (https://stackoverflow.com/questions/2237803/can-i-obtain-method-parameter-name-using-java-reflection)
"Code must be compiled with Java 8 compliant compiler with option to store formal parameter names turned on (-parameters option)."

How can I achieve this in B4J ?

Thanks!
 

Daestrum

Expert
Licensed User
Longtime User
Cut down version of what I use - but it should give you enough info to modify for your needs (Uses JavaObject Library)

You will see most names as Arg0, Arg1 etc. I use paranamer (the one in you posted link) to get better resolve of the parameter names at run time.

B4X:
Sub AppStart (Form1 As Form, Args() As String)
 MainForm = Form1
 'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
 MainForm.Show
 asJO(Me).RunMethod("getMethods",Array(Me))
End Sub
Sub asJO(o As JavaObject) As JavaObject
 Return o
End Sub
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
 Return True
End Sub
#if java
import java.lang.reflect.*;
public static void getMethods(Class c){
 Method[] m = c.getDeclaredMethods();
 for (Method mm : m){
  System.out.println("Method : "+mm);
  Type[] ex = mm.getGenericExceptionTypes();
  for (Type exc : ex){
   System.out.println("\tThrows : "+exc.getTypeName());
  }
  Class[] params = mm.getParameterTypes();
  for (Class p : params){
   if (p.isArray()){ 
    System.out.print("(Array)");
   } 
   System.out.println("\tParam : "+p.getCanonicalName().toString());
  }
  System.out.println("\tReturns : "+ mm.getReturnType().getSimpleName());
  System.out.println("-----Parameter names follow-------");
  Parameter[] parms = mm.getParameters();
  for (Parameter p : parms){
   System.out.println("parm names : "+p.getName());
  }
 }
}
#End If
 
Upvote 0
Top