Assigning values without using usual notation like "this.<Double>getAnything(int flag)"
private <T> T getAnything(int flag) {
Object o = null;
if (flag==0)
o=new String("NewString");
else if (flag==1)
o=new Double(0D);
return (T)o;
}
private void someMethod() {
String s = getAnything(0);
Double d = getAnything(1);
}
in the past it was enough only a return object on the method and a simple cast onthe receiveing type, so with the lacking of generic notation on the receiver object it is much more similar and fast to write, any other hint on this?
It's not clear what you're trying to do, but it should be pointed out that there's no typesafety what-so-ever in your code.
Double d = getAnything(0);
// compiles fine, but throws ClassCastException at run time
This defeats the purpose of using generics in the first place.
You introduced this unsafetiness when you wrote this statement:
return (T)o; // warning: Type safety: Unchecked cast from Object to T
SuppressWarnings (“unchecked”) in Java?Perhaps you want something like what Josh Bloch calls the Typesafe Heterogeneous Container. Here's a quote from Neal Gafter's blog:
Here is a simple but complete example of an API that uses type tokens in the THC pattern, from Josh's 2006 JavaOne talk:
public class Favorites { private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>(); public <T> void setFavorite(Class<T> klass, T thing) { favorites.put(klass, thing); } public <T> T getFavorite(Class<T> klass) { return klass.cast(favorites.get(klass)); } public static void main(String[] args) { Favorites f = new Favorites(); f.setFavorite(String.class, "Java"); f.setFavorite(Integer.class, 0xcafebabe); String s = f.getFavorite(String.class); int i = f.getFavorite(Integer.class); } }
With this pattern you get type-safety; int i = f.getFavorite(String.class); does NOT compile (which is a good thing!).
Autoboxing is the implicit conversion from say primitive int to reference type Integer; autounboxing is the opposite conversion. The question as stated has nothing to do with autoboxing.
int num = Integer.getInteger(“123”) throw NullPointerException?int and an Integer in Java/C#?boolean?new Integer(i) == i in Java? (YES!!!)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With