| Author |
Java Generics Warning
|
aanal jethalia
Greenhorn
Joined: Nov 16, 2006
Posts: 13
|
|
Hi I have a class which has a static method that takes a String classname and returns the instance of type class. My method looks like: public static <T extends Object> T getClassInstance(String className) throws Exception{ T instanceToReturn = null; try { Class c = Class.forName(className); instanceToReturn = (T)c.newInstance(); } catch (InstantiationException e) { throw e; } catch (IllegalAccessException e) { throw e; } catch (ClassNotFoundException e) { throw e; } return instanceToReturn; } I get the following warning: Type safety: The cast from Object to T is actually checking against the erased type Object. Should I be worried about this warning? How can I avoid it? I am very new to Generics, so am not sure if this is the correct way to use it. Any help would be great. Thanks Aanal
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
Sadly, the only way to get rid of that warning is by adding a @SuppressWarnings annotation to the method.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
I don't think there's anything sad about it. Ultimately, you get a warning because within that method, there's really no way to know that the String argument passed in will be compatible with the type T which must be inferred from the return type. If someone calls this method with String x = getClassInstance("java.lang.Integer"); it will fail, period. Whereas String x = getClassInstance("java.lang.String"); works fine. Only the calling code can determine if this will work; thus, it's in the calling code that the decision should be made as to whether to cast or not. Best to just drop the generic type T, and declare the method to return an Object. That's the only thing you can guarantee from within the method. Let the caller decide whether a cast is appropriate.
|
"I'm not back." - Bill Harding, Twister
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
I have a different remark on your code: Why are you catching all those exceptions if you're immediately re-throwing them? You don't need the try-catch block, your code looks cleaner and shorter if you leave it off: Or you could make it even shorter:
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
aanal jethalia
Greenhorn
Joined: Nov 16, 2006
Posts: 13
|
|
I wrap the Exception with my application specific Exception and throw it again. Thats why I catch and throw. Thanks for your help.
|
 |
 |
|
|
subject: Java Generics Warning
|
|
|