How I can get constructor reflectively, if its param is Object ... objects.
My constructor:
public MyClass ( Object ... objects )
{
if ( ! ( objects == null ) )
{
if ( objects.length > 0 && objects [ 0 ] instanceof Long )
{
setLatency ( ( Long ) objects [ 0 ] ) ;
}
}
}
How I get it now:
Class< ? > clazz = Class.forName ( "MyClass" ) ;
Constructor< ? > clazzConstructor = clazz.getConstructor ( Object [ ].class ) ;
What I try to do:
Long latency = 1000L ;
MyClass myInstance = ( MyClass ) clazzConstructor.newInstance ( latency ) ;
And I get
java.lang.IllegalArgumentException: argument type mismatch
If latency == null, everything works.
Your constructor is expecting an object array but you’re passing a single
Longto it.Wrapping
latencyinto an object array will work, although be careful asnewInstance()itself is expectingObject ..., and if you pass it nothing but anObject[], it will interpret it as a list of arguments. So you’ll have to do something like this:or
The first one “fools” the compiler into wrapping your object array into another, the second one does it explicitly instead.
(Passing null only worked because null is null, no matter what the declared type of the parameter is.)