Re: Create an Object from an Array Class
Z wrote:
I am using reflection to getmethod(methodName, Class parameters) and
invoke(object, obj[] parameters) methods from some Objects.
My problem is:
Say: I want to invoke a method that takes String[] object as parameter
(I was able to getmethod correctly). When I try to create an object
(to pass as args to invoke):
Object someObject= (Object) String[].class.newInstance();
(Note that the object is not always an instance of String[]... it
could be an instance of SomeOtherClass[])
RTFM:
[ From Class.newInstance(): ]
Throws:
[ ... ]
InstantiationException - if this Class represents an abstract
class, an interface, an array class, a primitive type, or void; or if
the class has no nullary constructor; or if the instantiation fails for
some other reason.
[ ... ]
Arrays cannot be created with a new instance, because they are a
special-case class.
My question is:
Does the "[L" at the beginning and the ";" at the end have a meaning?
Yes, this is the internal representation of the class (it means that
this is an array of java.lang.String's).
How can I solve this problem?
What you are probable intending is something like this:
Method m = Class.forName("some.pkg.Type").getMethod("main",
String[].class);
m.invoke(null, new String[0]);
I am using IntelliJ 6.0.5.
Java version matters, not IDE version.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth