Re: Generics and forName()
- From: Ian Pilcher <i.pilcher@xxxxxxxxxxx>
- Date: Tue, 31 Jan 2006 09:12:05 -0600
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
========================================================================
.
- References:
- Generics and forName()
- From: Jacob
- Generics and forName()
- Prev by Date: Re: signum of long
- Next by Date: Re: Any Checkstyle users?
- Previous by thread: Re: Generics and forName()
- Next by thread: What IDE for Java do you use?
- Index(es):
Relevant Pages
|