Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Generic Static Methods

I have been trying to understand whether it is possible to make a method which infers a generic type based on the return class and calls a static method of that generic type.

i.e. Below I create 2 classes both of which implement the getInstances and getAllInstances methods. I then attempt to create use the methods from a generic wrapper. It appears that the super class method is always being run regardless of the return type.

For example,

public class ParentClass {

    public ParentClass(){}

    public static <T extends ParentClass> T getInstance(){
        return (T) new ParentClass();
    }

    public static <T extends ParentClass> List<T> getAllInstances(){
        ArrayList<ParentClass> parents = new ArrayList<ParentClass>();

        for(int i=0;i<5;i++){
            parents.add(new ParentClass());
        }

        return (List<T>) parents;
    }

}

SubclassA

public class SubclassA extends ParentClass{

     public SubclassA(){}

    @SuppressWarnings("unchecked")
    public static SubclassA getInstance(){
         return new SubclassA();
    }

    @SuppressWarnings("unchecked")
    public static List<SubclassA> getAllInstances(){
        ArrayList<SubclassA> parents = new ArrayList<SubclassA>();

          for(int i=0;i<5;i++){
             parents.add(new SubclassA());
          }

         return parents;
      }
 }

Wrapper - Shows the problem

 public class Wrapper {

    public Wrapper(){
        // ... some other stuff
    }

    public <T extends ParentClass> T getInstance(){
        return T.getInstance();
    }

    public <T extends ParentClass> List<T> getAllInstances(){
        return T.getAllInstances();
    }

    public static void main(String... args){
        Wrapper wrapper = new Wrapper();

        SubclassA subclassA = wrapper.getInstance();
        ParentClass parentClass = wrapper.getInstance();

        System.out.println(subclassA.getClass().getName());
        System.out.println(parentClass.getClass().getName());
    }

 }

When running Wrapper I get the following error:

Exception in thread "main" java.lang.ClassCastException: ParentClass cannot be cast to SubclassA at Wrapper.main(Wrapper.java:20)

Can I do this in Java?

like image 460
user2294382 Avatar asked Apr 18 '13 09:04

user2294382


2 Answers

static methods will not be override.This static methods will belongs to Class level

like image 137
NPKR Avatar answered Oct 19 '22 18:10

NPKR


Your approach is incorrect, there is no notion of static Inheritance in Java as inheritance always is in context of Object level. Only member methods (non-static) can be inherited by sub classes having appropriate access modifiers.

Update: Further to add, in your scenario Factory pattern seems more suitable than adjusting generics for getting/constructing specific class objects.

like image 41
harsh Avatar answered Oct 19 '22 18:10

harsh