gpt4 book ai didi

Java 泛型 : Infering the type from another method?

转载 作者:行者123 更新时间:2023-12-01 06:18:26 26 4
gpt4 key购买 nike

我有一个装饰器,我想以特殊的方式使其通用。

用法:

            new ExceptionHandler() {
public <T extends IrcEvent> void doIt( T msg, IrcBotProxy pircBotProxy ) throws Throwable {
plugin.onMessage( msg, pircBotProxy );
}
}.handle( msg, this.pircBotProxy );

我希望从 .handle(...) 推断出 T,它获取特定的子类型 - IrcEvMsg

这怎么可能?或者我是否需要使用要使用的类型来参数化 ExceptionHandler ? (Java 7)

处理程序代码:(不会以这种方式编译 - 表示“Exceptionhandler 没有实现 doIt(...)”)

public abstract class ExceptionHandler {

public <T extends IrcEvent> void handle( /*IIrcPluginHook plugin,*/ T evt, IrcBotProxy pircBotProxy ) {
try {
this.doIt( evt, pircBotProxy );
}
catch( NullPointerException ex ) {
log.error( "Plugin misbehaved: " + ex, ex );
}
catch ( Throwable ex ) {
if( System.getProperty("bot.irc.plugins.noStackTraces") == null ) {
log.error("Plugin misbehaved: " + ex.getMessage(), ex);
} else {
log.error("Plugin misbehaved: " + ex);
if (ex.getCause() != null) {
log.error(" Cause: " + ex.getCause());
}
}
}
}

public abstract <T extends IrcEvent> void doIt( T event, IrcBotProxy pircBotProxy ) throws Throwable;

}// class

最佳答案

按照您的方式推断类型没有问题。这是一个非常简单的示例,演示了:

public abstract class ExceptionHandler
{
public <T extends List> void handle(T l) {
this.doIt(l);
}

public abstract <T extends List> void doIt(T l);
}

...

public class Demo
{

public static void main(String[] args)
{
new ExceptionHandler() {

@Override
public <T extends List> void doIt(T l)
{
System.out.println(l.size());
}

}.handle(new ArrayList<String>(Arrays.asList(new String[] { "hi" } )));
}
}

输出:

1

您声明您收到编译错误“ExceptionHandler未实现doIt(...)” - 您需要重新检查您的代码并确保您传递了正确的params,确保文件已保存,然后清理并重建项目。

关于Java 泛型 : Infering the type from another method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17637228/

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