gpt4 book ai didi

Java 泛型不适用于参数问题

转载 作者:行者123 更新时间:2023-11-30 08:03:43 25 4
gpt4 key购买 nike

我在编写通用框架时遇到问题。有人可以向我解释为什么我的代码无法编译吗?我试图用这个简单的例子来展示它。 (更新示例)

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

public class TestGeneric {

public static void main(String... sss) throws Exception {

Dao dao = new Dao("Hello");
dao.extend();

System.out.println(dao.getHelloWorld());
}
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation {

public Class<? extends AbstractCommand<? extends AbstractDao>>[] commands() default {};
}

abstract class AbstractDao {

public void extend() throws Exception {

for (Field field : this.getClass().getDeclaredFields()) {

if (field.isAnnotationPresent(TestAnnotation.class)) {

TestAnnotation annotation = field.getAnnotation(TestAnnotation.class);

for (Class<? extends AbstractCommand<? extends AbstractDao>> commandClass : annotation.commands()) {

AbstractCommand<? extends AbstractDao> command = commandClass.newInstance();
command.doSomething(this);
}
}
}
}
}

class Dao extends AbstractDao {

@TestAnnotation(commands = { Command.class })
private String hello;

private String world;

public Dao(String hello) {
this.hello = hello;
}

public String getHello() {
return this.hello;
}

public void setWorld(String world) {
this.world = world;
}

public String getHelloWorld() {
return this.hello + " " + this.world;
}
}

abstract class AbstractCommand<T extends AbstractDao> {
public abstract void doSomething(T t);
}

class Command extends AbstractCommand<Dao> {

@Override
public void doSomething(Dao t) {

if (t.getHello().equals("Hello")) {
t.setWorld("World");
}
}
}

一旦我做出以下更改......

abstract class AbstractCommand<T extends AbstractDao> {
public abstract void print(AbstractDao t);
}

class Command extends AbstractCommand<Dao> {

@Override
public void doSomething(AbstractDao t) {

Dao dao = (Dao) t;

if (dao.getHello().equals("Hello")) {
dao.setWorld("World");
}
}
}

...一切正常,但我必须一直使用 AbstractDao。

据我所知,一切都应该保存,但我一直收到这个错误。

The method print(capture#3-of ? extends AbstractDao) in the type AbstractCommand is not applicable for the arguments (Dao)

但是Dao扩展了AbstractDao,那么问题到底出在哪里呢?

我已经找到了这个问题generics error: not applicable for the arguments但我不确定这是否与我遇到的问题相同。

我的猜测是它与“Because the Java compiler erases all type parameters in generic code, you cannot verify which parameterized type for a generic type is being used at runtime”有关'

有人能解决这个问题吗?

谢谢!

最佳答案

您正在使用 AbstractCommand 引用。

试试这个

((Command)command).print(new Dao("Hello World"));

关于Java 泛型不适用于参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36105061/

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