从如何获得Java中8的方法参数名称使用反射?
我知道使用javac -parameters
参数可以将参数名保存在*.class文件中.但它在lambda表达式中无效?
例:
import java.lang.reflect.Method; import java.lang.reflect.Parameter; public class MyTest { public static void main(String[] args) { for(Method m : Test.class.getDeclaredMethods()) { System.out.println(m.getName()); for(Parameter p : m.getParameters()) { System.out.println(" => " + p.getName()); } } } } interface MyInterface { Object doSomething(int a, int b); } class Test { private void bar(MyInterface iface) { } public void foo() { bar((x, y) -> null); } }
当我做
javac -parameters MyTest.java java MyTest
它打印
bar => iface foo lambda$foo$0 => arg0 => arg1
我尝试做javap -c -p -verbose Test
:
{ Test(); descriptor: ()V flags: Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokespecial #1 // Method java/lang/Object."":()V 4: return LineNumberTable: line 21: 0 private void bar(MyInterface); descriptor: (LMyInterface;)V flags: ACC_PRIVATE Code: stack=0, locals=2, args_size=2 0: return LineNumberTable: line 24: 0 MethodParameters: Name Flags iface public void foo(); descriptor: ()V flags: ACC_PUBLIC Code: stack=2, locals=1, args_size=1 0: aload_0 1: invokedynamic #2, 0 // InvokeDynamic #0:doSomething:()LMyInterface; 6: invokespecial #3 // Method bar:(LMyInterface;)V 9: return LineNumberTable: line 27: 0 line 28: 9 private static java.lang.Object lambda$foo$0(int, int); descriptor: (II)Ljava/lang/Object; flags: ACC_PRIVATE, ACC_STATIC, ACC_SYNTHETIC Code: stack=1, locals=2, args_size=2 0: aconst_null 1: areturn LineNumberTable: line 27: 0 }
我可以找到参数名称iface
,但找不到x
或y