-2

If I have the method like public int sum(int a, int b, int c) { }

Answer: Parameters count is 3

Methods having parameters has not fixed, sometimes it might be 2 or 1 or 4 How to find out this through Java code ?

castis
  • 8,154
  • 4
  • 41
  • 63
  • It's not clear what you mean by "any method". If you know the method you also now the number of parameters unless it has a vararg argument, whereas the linked question would help you. If you don't know the method and you just want to inspect the signatures of methods of an unknown class you could use reflection, but then you should clarify your question. – David Ongaro Sep 14 '18 at 22:35
  • public void countOfMethodParameters(String a, int b) { System.out.println(a+" "+b); } public static void main(String[] args) throws NoSuchMethodException{ Class demoObject = demo.class; Method method = demoObject.getMethod("countOfMethodParameters", String.class, int.class); System.out.println("Method Name= "+method.getName()); System.out.println("Method parameter Count= "+method.getParameterCount()); } – Akshay Kulkarni Aug 14 '19 at 11:06
  • We can use reflections – Akshay Kulkarni Aug 14 '19 at 11:09

1 Answers1

1

You can use optional param.

private static void sum(int... params) {
    System.out.println(params.length);
    //some logic
}

Use this method whatever you want. Forexample ;

sum(1,2,3); // it returns 3
sum(1,2);   // it returns 2 
sum(1,2,29,323,123); // it returns 5 
sum(1,2,3,4,5,6,7,8); // it returns 8 

In sum method , your parameters are set in int array . Also you can get like

params[0] // this refers first param
params[1] // this refers second param
//and others. 

Please be careful on arraylength when getting parameter. Dont get exception.

drowny
  • 2,067
  • 11
  • 19