gpt4 book ai didi

Java 有界类型

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:24:17 25 4
gpt4 key购买 nike

我正在尝试理解 Java 中的有界类型。我认为我的推理几乎是正确的,但我得到了一个错误,我不明白为什么如果 A (JsonPerson) 是 T (Person) 的子类,它会给我这个错误。错误如下(代码中也有注释):

Error:(22, 16) error: incompatible types: JsonPerson cannot be converted to A
where A is a type-variable:
A extends Person declared in method <A>fromJson(JSONObject)

错误“发生”在返回行中。

我做了一个简单的例子,下面是代码

Person.java

public class Person {

private String name;

private String surname1;

private String surname2;

private String phone;

private String email;

public Person(String name, String surname1, String surname2, String phone, String email) {
this.name = name;
this.surname1 = surname1;
this.surname2 = surname2;
this.phone = phone;
this.email = email;
}

public String getName() {
return name;
}

public String getSurname1() {
return surname1;
}

public String getSurname2() {
return surname2;
}

public String getPhone() {
return phone;
}

public String getEmail() {
return email;
}

}

JsonPerson.Java

public class JsonPerson extends Person implements JSONSerializableInterface<Person> {

public JsonPerson(String name, String surname1, String surname2, String phone, String email) {
super(name, surname1, surname2, phone, email);
}

/**
* Error:(22, 16) error: incompatible types: JsonPerson cannot be converted to A
* where A is a type-variable:
* A extends Person declared in method <A>fromJson(JSONObject)
* */
@Override
public <A extends Person> A fromJson(JSONObject json) throws JSONException {
String name = json.getString("name");
String surname1 = json.getString("surname1");
String surname2 = json.getString("surname2");
String phone = json.getString("phone");
String email = json.getString("email");
return new JsonPerson(name, surname1, surname2, phone, email);
}

@Override
public JSONObject toJson(Person object) {
return null;
}
}

JSONSerializableInterdace.java

public interface JSONSerializableInterface<T> {

public <A extends T> A fromJson(JSONObject json) throws JSONException;

public JSONObject toJson(T object);
}

最佳答案

问题是有人可能会这样调用你的方法:

new JSONPerson().fromJSON<SpecialPerson>(json);

其中 SpecialPerson 扩展 Person。这是有效的(因为 A 扩展了 Person),但是该方法返回的 JSONPerson 不是 SpecialPerson .

关于Java 有界类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31743190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com