简体   繁体   中英

How do i implement a generic class that calls a static method of specified interface in java

I have the following code, which does not work as intended. When I call the Chumbles constructor with Grumbo as type it calls every time the static method of the Schlami interface instead of the method of Grumbo. What am I missing here? and what workaround, and I am pretty sure I need one, should I implement?

Thanks in advance!

ps: I feel already sorry for my naming convention

EDIT: my intention: I have several classes that all need to be converted to JSON and from JSON back into a class. additional to that I have a wrapper class for each of them that holds an array list of the classtype and can convert that list back and forth to JSON.

so I tried to build an generic class that I can reuse to minify code. my attempt was to implement an interface that guarantees the existence of both methods and to call them in that generic class. but this seems not to work.

in know that the object cast doesn't work. that function should never be called anyway

public class main {

    public static void main(String[] args){

        Chumbles<Grumbo> schleem = new Chumbles<>("test");

        System.out.println("pause");
    }
}
public class Chumbles<T extends Schlami> {

    public Chumbles(String s){

        T fleeb = T.fromJSON(s);
        System.out.println(fleeb.toJSON());
    }
}
public class Grumbo implements Schlami {

    String s;

    public Grumbo(String s) {
        this.s = s;
    }

    @Override
    public String toJSON() {
        return "GrumboJSON";
    }

    public static Grumbo fromJSON(String s) {
        return new Grumbo("Grumbo Success ");
    }
}
public interface Schlami {

    String toJSON();

    static <T> T fromJSON(String json){

        return (T) new Object();
    }
}

EDIT2: so I use now a combination of generic factoryclasses and non static call of fromJSON. it feels gross to use new Grumbo().fromJSON(json) but I'll use it till I find a better workaround. thanks everyone for helping.

So, your question is why at "T.fromJSON(s);" the method from Schlami instead of the method from Grumbo is called? Since T extends Schlami, Schlami is always the class referenced when calling static methods. Please note, that you cannot override static methods!

I would suggest just calling the method by "Grumbo.fromJSON();". If you need to override the method, you could turn Schlami in an abstract class, override the method in Grumbo and call it from object-context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM