Re: Generics and forName()



Jacob wrote:
> 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.

In this case, you can use Class.asSubclass:

Class<A> clazz = Class.forName("A").asSubclass(A.class);

As Tony pointed out, there are perfectly valid (and sometimes
unavoidable) constructs which will produce unchecked cast warnings.
Read up on the @SuppressWarnings annotation, and note that Sun's
compiler didn't support it until 1.5.0_06.

I'm assuming that the code you posted is a contrived example. If not,
Roedy's comment is right on; there's no reason to use Class.forName for
a known type.

HTH

--
========================================================================
Ian Pilcher i.pilcher@xxxxxxxxxxx
========================================================================
.



Relevant Pages