Java how to call method by reflection with primitive types as arguments

前端 未结 2 949
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 12:53

I have the following two methods in a class:

public void Test(int i){
    System.out.println(\"1\");
}
public void Test(Integer i){
    System.out.println(\"         


        
相关标签:
2条回答
  • 2020-12-05 13:12

    To call a method with primitive types as parameters using reflection :

    You could use int.class

    this.getClass().getMethod("Test",int.class).invoke(this, 10);
    

    or Integer.TYPE

    this.getClass().getMethod("Test",Integer.TYPE).invoke(this, 10);
    

    same applies for other primitive types

    0 讨论(0)
  • 2020-12-05 13:12

    Strange but true:

    this.getClass().getMethod("Test",int.class).invoke(this, 10);
    
    0 讨论(0)
提交回复
热议问题