Ankit
Ankit

Reputation: 6622

how to write it in generics way?

I have an interface, Parseable. in which I have method which should return the object of implementing method. Say,

P1 implements Parseable {
    P1 fromJson(JSONObject){}
}

it is giving unsafe type warning with this below signature. how can I fix it?

<T> T fromJson(JSONObject)

Upvotes: 2

Views: 89

Answers (3)

Eran
Eran

Reputation: 393781

Make the interface itself generic instead of the method.

Declare Parseable as :

public interface Parseable<T> {
    public T fromJson(JSONObject obj);
}

And P1 :

public class P1 implements Parseable<P1> {
    @Override
    public P1 fromJson(JSONObject obj){}
}

Upvotes: 4

EpicPandaForce
EpicPandaForce

Reputation: 81539

public interface Parseable<T> {
    T fromJson(JSONObject js);
} 

P1 implements Parseable<P1> {
    P1 fromJson(JSONObject js) { ... }
}

Upvotes: 1

Seelenvirtuose
Seelenvirtuose

Reputation: 20618

Well. The interface needs to look as

public interface Parseable<T> {
    T fromJson(JSONObject json);
}

And your class looks as following:

public class P1 implements Parseable<P1> {
    @Override public P1 fromJson(JSONObject json) { ... }
}

Upvotes: 2

Related Questions