T
Tony Morris
Jacob said:If I have this class:
class A {
public A(String a);
}
Is it possible to make an instance through reflection without getting a
compiler warning (java 1.5)?
The following gives an unchecked warning in the first line due to the
forced cast. Using "?" just postpone the the problem:
Class<A> clazz = (Class<A>) Class.forName("A");
Constructor<A> ctor = clazz.getConstructor(String.class);
A a = ctor.newInstance("hello world");
The problem is that in my organization we treat warnings as errors and
the above simply isn't doable within such a regime.
What is the workaround?
(And why whould all the above be possible (by Class<?> and Class.newInstance()),
if just the constructor didn't take any arguments?)
Thanks!
Hello Jacob,
I have seen this question quite a number of times, which prompted me to add
it to my FAQ.
http://jqa.tmorris.net/GetQAndA.action?qids=80&showAnswers=true
I have also included a code sample below that demonstrates what you want to
achieve.
As a note, if you have a policy of not being permitted to have compile-time
warnings, it may be in your interest to learn about generics.
Also note that there are some valid use cases that force a compile-time
warning, due to the contrived nature of the Java generics implementation, so
you may seek to have this policy reviewed. These forced use cases are the
result of the introduction of failure to maintain a conversion between
arrays and parameterised types (without a warning) - as an example, take a
look at the java.util.ArrayList implementation, which is backed by an
array - you will note that there is a forced compile-time warning. You
discover these nitty details when you implement the spec. after a JSR
"expert" group has been onto the case I did make this issue known well
before the spec. was released, but the most plausible response I got was
"oops".
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static java.lang.Class.forName;
class X
{
X(final String s)
{
}
}
final class Main
{
private Main() throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
public static void main(final String... args) throws
ClassNotFoundException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
InvocationTargetException
{
final Class<?> c = forName("X");
final Class<? extends X> xc = c.asSubclass(X.class);
final Constructor<? extends X> ctor =
xc.getConstructor(String.class);
final X x = ctor.newInstance(args[0]);
}
}
--
Tony Morris
http://tmorris.net/
Java Questions and Answers
http://jqa.tmorris.net/