General method without parameters

I was confused with my code, which includes a generic method that takes no parameters, so what will be the returned generic type of such a method, for example:

static <T> example<T> getObj() {
    return new example<T>() {

        public T getObject() {
            return null;
        }

    };
}

and this was called through:

example<String> exm = getObj(); // it accepts anything String like in this case or Object and everything

protection example's:

public interface example<T> {

    T getObject();
}

My question is: example<String> exmaccepts String, Object and all. So, at what time is the typical return type indicated as String and how?

+2
source share
2 answers

The compiler infers the type Tfrom the specific type used in the LHS assignment.

From this link :

, . , , . , .

:

public final class Utilities { 
  ... 
  public static <T> HashSet<T> create(int size) {  
    return new HashSet<T>(size);  
  } 
} 
public final class Test 
  public static void main(String[] args) { 
    HashSet<Integer> hi = Utilities.create(10); // T is inferred from LHS to be `Integer`
  } 
}
+8

, :

example<String> x = getObj();
String s = x.getObject();//no casting required, good!

BUT getObject , return:

public T getObject() {
//how would this method return based on T?
//one way to always cast to T say: 
   //return (T) obj; 
   // but do you figure out obj based on T, NOT possible! due to type eraser at runtime
   // a custom logic can produce diff type obj, but that force casting and no generic usage

                return null;
            }

T Class:

public <T> T getObject(Class<T> clazz) {
//clazz can be used to derive return value
..
}
0

All Articles