告诉编译器<Object>等同于它想要的<?>

如何解决告诉编译器<Object>等同于它想要的<?>

我有一些对象会预先生成一些配置,因此它们以后可以更快地处理计算(可能是几次)。我正在尝试对其进行通用化,以避免将配置作为Object传递并每次进行转换。

interface IComputable<T> {
    T configure(); // Generate configuration object
    int compute(T conf); // Run the computation based on the pre-generated configuration
    float precision(T conf); // Make the compute() computation finer-grained
    ...
}
class ComputableInfo {
    IComputable<?> computable;
    Object config; // Real type is <?>
    int result;

    ComputableInfo(String id) {
        computable = ComputableFactory.createFrom(id);
        config = computable.configure();
        result = computable.compute(config); // <<<--- The method compute(capture#3-of ?) in the type TestInterface.IComputable<capture#3-of ?> is not applicable for the arguments (Object)
    }
}

我遇到编译错误:

类型为TestInterface.IComputable 的方法compute(capture#3-of?)不适用于参数(Object)

当然,我可以将int compute(T conf)替换为int compute(Object conf),但必须将其显式转换为适当的T。这不是什么大问题,但是它使代码不那么明显。

我也可以使用{p>

ComputableInfo

但这会在其他一些地方引起编译问题(主要是“原始类型”警告),我希望避免使用比以前的解决方法更多的方法(使用interface ComputableInfo<T> { IComputable<T> computable; T config; ... 而不是Object)。 / p>

有没有办法做到这一点?我什至愿意在编译器设置中将此类问题从错误转变为警告,或者有一个额外的私有方法可以在单个对象中同时返回Tconfig

编辑:如果我将result设为泛型,则将“进一步的编译问题”加起来:接口中有另一种方法,通过ComputableInfo来调用(参见编辑):

ComputableInfo

问题是ComputableInfo<?> info = getInfo(id); info.computable.precision(info.config); // <<<--- (same kind of error) 无法知道ComputableInfo的{​​{1}}类型(或者我无法知道),因为它来自工厂,工厂是通过配置文件。

解决方法

从通配类型获取对象并将其传递回同一对象是通用类型系统的已知限制。例如,当您拥有

List<?> list = …

您可能希望将元素从一个索引复制到另一个索引,例如

Object o = list.get(0);
list.set(1,o);

,但即使您避免使用不可表示类型的局部变量,它也无法正常工作。换句话说,即使以下内容也无法编译:

list.set(1,list.get(0));

但是您可以添加一个通用的辅助方法来执行该操作,方法是允许在操作期间捕获类型参数中的通配符类型:

static <T> void copyFromTo(List<T> l,int from,int to) {
    l.set(to,l.get(from));
}
List<?> list = …
copyFromTo(list,1); // now works

您也可以将此模式应用于您的案例:

class ComputableInfo {
    IComputable<?> computable;
    Object config; // Real type is <?>
    int result;

    ComputableInfo(String id) {
        computable = ComputableFactory.createFrom(id);
        configureAndCompute(computable);
    }

    private <T> void configureAndCompute(IComputable<T> computable) {
        T typedConfig = computable.configure();
        this.config = typedConfig;
        this.result = computable.compute(typedConfig);
    }
}

这有效,不需要将ComputableInfo设为通用。

如果您需要捕获类型的时间长于单个方法,例如如果要多次使用创建的config,可以使用封装:

class ComputableInfo {
    static final class CompState<T> {
        IComputable<T> computable;
        T config;

        CompState(IComputable<T> c) {
            computable = c;
        }
        private void configure() {
            config = computable.configure();
        }
        private int compute() {
            return computable.compute(config);
        }
    }
    CompState<?> state;
    int result;

    ComputableInfo(String id) {
        state = new CompState<>(ComputableFactory.createFrom(id));
        state.configure();
        result = state.compute();
    }
}

这样,您仍然避免将类型参数导出到ComputableInfo的用户。

,

您需要使用下界通配符。 Object与通配符?本身不兼容。

class ComputableInfo {
    IComputable<? super Object> computable;
    Object config;
    int result;

    ComputableInfo(String id) {
         computable = null;
         config = computable.configure();
         result = computable.compute(config);
    }
}

下限指出IComputable将是Object的实例,或者某个对象的实例是Object的超类(实际上,该对象是所有{{ 1}})。为了更好地理解,让我们使用Objects

Number

但是,将IComputable<Integer> computableInteger = ...; IComputable<Number> computableNumber = ...; IComputable<Object> computableObject = ...; IComputable<? super Number> computableSuperNumber = ...; computableSuperNumber = computableInteger; // doesn't compile computableSuperNumber = computableNumber; // ok computableSuperNumber = computableObject; // ok Integer传递到该实例的方法中是安全的。在Double下面的代码段中引用了一个computableSuperObject ,它可能是以下其中之一:

  • IComputable
  • IComputable<Number>

由于引用可能IComputable<Object>,因此,只要IComputable<Number>可以存在,则使用Object进行计算是非法的。 Object

String

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-