lundi 30 juillet 2018

Reflection - Invoke method with Long and Number args

I have the following method in a class called NumberToStringConverter:

public String convert(Number input) {
  return String.valueOf(input);
}

I want to invoke the methode with the following code:

NumberToStringConverter obj = new NumberToStringConverter();
Method m = obj.getClass().getMethod("convert", new Class[] { Long.class });
m.invoke(obj, new Object[] { aLongObject });

The thing is, I get the following error:

java.lang.NoSuchMethodException: NumberToStringConverter.convert(java.lang.Long) 

When you write your own code, Java allows invoking a method that has a Number argument with a Long argument. It automatically converts the Long into a Number object. Why doesn't this match happen with reflection? And how can I make it work?





Aucun commentaire:

Enregistrer un commentaire