Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: Generic type defined as return type only

I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is com.extjs.gxt.ui.client.data.BaseModelData if you want to look at all of the code. Here are the important parts:

private RpcMap map;  public <X> X get(String property) {   if (allowNestedValues && NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); } 

X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the <X> in the public method signature.

I've tried to call this method with the following two examples to see what happens:

public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); } 

They compile and show no errors or warnings. I would think at the very least I would have to do a cast to get this to work.

Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime? This seems counter to what generics are supposed to do. Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better? I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.

like image 951
Jason Tholstrup Avatar asked Dec 03 '08 21:12

Jason Tholstrup


People also ask

Can a generic class definition can only have one type parameter?

A generic method can have one or more type parameters, such as the "T" in countOccurrences.

How do you define generic type?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.


1 Answers

The method returns a type of whatever you expect it to be (<X> is defined in the method and is absolutely unbounded).

This is very, very dangerous as no provision is made that the return type actually matches the returned value.

The only advantage this has is that you don't have to cast the return value of such generic lookup methods that can return any type.

I'd say: use such constructs with care, because you lose pretty much all type-safety and gain only that you don't have to write an explicit cast at each call to get().

And yes: this pretty much is black magic that blows up at runtime and breaks the entire idea of what generics should achieve.

like image 170
Joachim Sauer Avatar answered Sep 22 '22 19:09

Joachim Sauer