This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Class and generics Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Class and generics" Watch "Class and generics" New topic
Author

Class and generics

Andrey Kozhanov
Ranch Hand

Joined: Mar 12, 2010
Posts: 79
Hello!

My goal is to create object by it's name using non-default constructor.

Let's consider the following simple "hello world" program to do this:



With Java 1.6 it works fine, but gives compile time warning:

Note: Hello.java uses unchecked or unsafe operation
Note: Recompile with -Xlint:unchecked for details.

I know the problem is with generics, specifically here: clazz.getDeclaredConstructor(new Class[] {java.lang.String.class}); But how should i change this line to avoid warning?
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Either use the compiler option or @SuppressWarnings("unchecked"). If you add the cast I think you'd get an unchecked cast warning, which means you'd have to do the same thing anyway. You could also make the clazz declaration generic and put the suppression there, and generify the Constructor init.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

You can do something like this, which compiles cleanly, with no annotations. It's really the Class.forName() which prevents you from doing this any other way.



[Jess in Action][AskingGoodQuestions]
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Oh; I like that better. (Although is the arg list <?> necessary?)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

David Newton wrote: (Although is the arg list <?> necessary?)


No, I guess not -- I got carried away
Andrey Kozhanov
Ranch Hand

Joined: Mar 12, 2010
Posts: 79
Ernest Friedman-Hill wrote:You can do something like this, which compiles cleanly, with no annotations. It's really the Class.forName() which prevents you from doing this any other way.


Yup, it worked. Thanks a lot!
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Class and generics
 
Similar Threads
Generics
Generics
generics
Generics