0

I try to make the generic method for other class. But I got a error
cannot be referenced from a static context
How to do the generics method for GetInstance

public class Instance<T> {

    private static final Instance<?> mInstance = new Instance<>(null);

    @SuppressWarnings("unchecked")
    public static Instance<T> GetInstance() { //Got error
        // Make generic static instance.
        // Strategy used similar to Collections.emptyList() implementation
        return (Instance<T>) mInstance; //Got Error
    }

    protected Instance(Context context) {

    }
}


 public static DataController GetDataController(@Nullable  Context context) {
    DataController dataController = (DataController) DataController.GetInstance();
    if(dataController == null) {
        return new DataController(context);
    }

    return dataController;
}

2 Answers2

0

Try this. It's the ancient druid magic

public static <T> Instance<T> GetInstance() {
    return (Instance<T>) mInstance;
}
Zeon
  • 535
  • 8
  • 23
0

Static methods are poperty of the class rather than of an instance of the class and therefore the generic of the class cannot be referenced.

However you can still create a generic method by adding a type reference directly to the method:

public static <T> Instance<T> GetInstance() {...}

And even bound it:

public static <T extends Comparable<T>> Instance<T> GetInstance() {...}

However to call such a method you maybe need to pass the type argument if the compiler can't infer it by itself:

Instance.<Integer> GetInstance();
L.Spillner
  • 1,772
  • 10
  • 19