从方法返回Java有界通用对象(Returning Java bounded generic objects from method)

我知道Oracle教程和问题, 如何使方法返回类型通用? 但是我仍然无法从Java方法返回通用对象。

简要示例:我有一个网络Packet的层次结构和Handler的层次结构,参数Packet它们处理的Packet 。 最后我有一个Handler注册表 ,其中包含一个方法,它会返回给定数据包的正确处理程序。

我想实现所有这一切,理想情况下没有警告手动压制。

class Packet {}
class ThisPacket extends Packet {}
class ThatPacket extends Packet {}

interface PacketHandler<P extends Packet> {
    boolean handle(P p);
}

class ThisPacketHandler extends PacketHandler<ThisPacket> {
    boolean handle(ThisPacket p);
}

class ThatPacketHandler extends PacketHandler<ThatPacket> {
    boolean handle(ThatPacket p);
}

这是非常规则的我相信,在我的实现中,我在中间有一些进一步的抽象类来塑造我的层次结构,但我认为现在可以忽略它。

关键部分是i)注册表:

class HandlersRegistry {
    static <<RETURN TYPE>> getHandler(Packet p) {
        if (p instanceof ThisPacket) return new ThisPacketHandler();
        if (p instanceof ThatPacket) return new ThatPacketHandler();
        return null;
    }
}

<<RETURN TYPE>> OPTIONS (I tried):
    // Raw-type Warning:
    A. PacketHandler 
    // the registry user won't be able to use the handler:
    B. PacketHandler<? extends Packet>
    // Type mismatch: cannot convert from 
    C. PacketHandler<Packet> 

..和ii)和注册用户:

class HandlerSwitchExample {
    public static void main() {
        // [...]
        <<OBJECT TYPE>> handler = HandlersRegistry.getHandler(somePacket);
        handler.handle(somePacket);
    }
}

希望这个例子相当清楚。 感谢任何有用的建议,甚至完整的重新设计策略。


I am aware of Oracle tutorials and questions like How do I make the method return type generic? but still I am having trouble returning generic objects from a Java method.

Brief example: I have a hierarchy of network Packets and a hierarchy of Handlers, parametrized to the Packet they handle. Eventually I have a registry of Handlers which includes a method to that would return me the proper handler of a given packet.

I would like to implement all of this with ideally no warning to manually suppress.

class Packet {}
class ThisPacket extends Packet {}
class ThatPacket extends Packet {}

interface PacketHandler<P extends Packet> {
    boolean handle(P p);
}

class ThisPacketHandler extends PacketHandler<ThisPacket> {
    boolean handle(ThisPacket p);
}

class ThatPacketHandler extends PacketHandler<ThatPacket> {
    boolean handle(ThatPacket p);
}

This is quite regular I believe, in my implementation I have some further abstract classes in the middle to shape my hierarchy, but I think this can be ignored by now.

The critical part is i) the registry:

class HandlersRegistry {
    static <<RETURN TYPE>> getHandler(Packet p) {
        if (p instanceof ThisPacket) return new ThisPacketHandler();
        if (p instanceof ThatPacket) return new ThatPacketHandler();
        return null;
    }
}

<<RETURN TYPE>> OPTIONS (I tried):
    // Raw-type Warning:
    A. PacketHandler 
    // the registry user won't be able to use the handler:
    B. PacketHandler<? extends Packet>
    // Type mismatch: cannot convert from 
    C. PacketHandler<Packet> 

..and ii) and the registry user:

class HandlerSwitchExample {
    public static void main() {
        // [...]
        <<OBJECT TYPE>> handler = HandlersRegistry.getHandler(somePacket);
        handler.handle(somePacket);
    }
}

Hope the example is fairly clear. Thanks for any helpful suggestion, even complete redesign strategies.


原文:https://stackoverflow.com/questions/29119731
2023-11-19 06:11

满意答案

没有什么明显的。 我会尝试修剪代码,直到它按预期下滑。 删除回调,删除html-set,删除成功/警告类设置器,在输出到控制台之前选择note元素,用立即显示替换幻灯片等。


首先尝试在注释上调用.stop(true,true)note.stop(true,true).slideDown(); 。 这是因为它忙于其他一些动画并且正在排队下滑。


Nothing obvious there. I would try trimming the code down until it slides down as expected. Remove the callback, remove the html-set, remove the success/warning class-setters, select the note-element before outputting to the console, replace the slide with an immediate show, etc.


Also try calling .stop(true,true) on the note first: note.stop(true,true).slideDown();. This is in case it is busy with some other animation and the slide down is being queued.

相关问答

更多

悬停时停止通知超时(Stop notification timeout on hover)

window.setTimeout()返回一个整数timerID,可以与window.clearTimeout() : var notificationTimer; function createTimer() { notificationTimer = setTimeout(function(){ alert('hi'); }, 10000); } function clearTimer() { clearTimeout(notificationTimer); } 另见: http...

jquery addClass - 等待,延迟,速度,超时或其他(jquery addClass - wait, delay, speed, timeout or other)

我不明白为什么hoverIntent不起作用: $("#menu ul li").hoverIntent({ sensitivity: 3, // number = sensitivity threshold (must be 1 or higher) interval: 200, // number = milliseconds for onMouseOver polling interval timeout: 500, // number = m...

在初始化之前设置延迟或超时(Set delay or timeout before initializing)

你有这个: $(document).ready(function() { 把这个: $(document).ready(function() { setTimeout(function() { 然后你有这个: }); // wrapper for background animation functionality var BG = { 把这个: }, 2000); }); // wrapper for background animation functionality...

在ssrs中延迟通知问题(Delay notification issue in ssrs)

标准IT修复。 关闭电脑,然后再打开 Standard IT fix. Turn your PC off and on again

使用jquery延迟(using jquery delay)

delay()只能用于动画,而不能用于像removeClass这样的函数,因为你需要一个timeOut。 不仅如此,Ajax调用也是异步的,所以您的类会立即被删除,并且不会等待Ajax调用完成。 你总是可以这样做: $(function(){ $(document).on('click', '.plus', function(e){ e.preventDefault(); var self = this, existingPath ...

Ajax jquery需要加载超时或延迟(Need a timeout or delay on loading, Ajax jquery)

$('body').delay(2000).queue(function( nxt ) { $(this).load('home.php'); nxt(); }); $('body').delay(2000).queue(function( nxt ) { $(this).load('home.php'); nxt(); });

jQuery:具有通知功能的超时/延迟?(jQuery: Timeout/Delay with a notification function?)

没有什么明显的。 我会尝试修剪代码,直到它按预期下滑。 删除回调,删除html-set,删除成功/警告类设置器,在输出到控制台之前选择note元素,用立即显示替换幻灯片等。 首先尝试在注释上调用.stop(true,true) : note.stop(true,true).slideDown(); 。 这是因为它忙于其他一些动画并且正在排队下滑。 Nothing obvious there. I would try trimming the code down until it slides do...

jQuery超时功能无法正常工作(jQuery Timeout Function not working)

你不能只调用clearTimeout() (顺便说一句,它不是JQuery的一部分),你必须为它提供一个你要取消的计时器的标识符。 此外, setTimeout()和clearTimeout()不是JQuery或JavaScript的一部分。 它们是window对象的方法,由浏览器提供。 它们不是语言(JavaScript)或库(JQuery)的一部分。 另外, JQuery .hover()方法接受2个参数,你提供4.我已将它们组合在下面,但不知道你想要做什么,你可能需要调整它。 $(docum...

使用jquery设置延迟或超时(Setting delay or timeout with jquery)

你可以这样做: $('.showmenu') .bind("mouseenter", function (e) { if($(this).data("timer")) clearTimeout($(this).data("timer")); $('ul.secondul').show(); }) .bind("mouseleave", function (e) { $(this).data("timer", setTimeout(function(){ ...

相关文章

更多

Guava Objects类详解

Objects.toStringHelper(s1)

java通用返回对象

java通用返回对象返回对象通常包括是否成功、响应码、接口响应描述、响应实体几个属性

Solr Cache使用介绍及分析,包括LRUCache、filterCache、queryResultCache、documentCache、Generic Caches

本文将介绍Solr查询中涉及到的Cache使用及相关的实现。Solr查询的核心类就是SolrIndex ...

java分页返回对象

分页对象通常包括总记录数和对象类别,如果像搜索引擎那样展示前后几个分页按钮,可以把展示的开始页和介绍页 ...

研磨设计模式之工厂方法模式(Factory Method)-场景问题

1.1 导出数据的应用框架,考虑这样一个实际应用:实现一个导出数据的应用框架,来让客户选择数据的导出 ...

研磨设计模式之工厂方法模式(Factory Method)-模式讲解2

3.2 工厂方法模式与IoC/DI,IoC——Inversion of Control 控制反转, ...

Java 方法

Java 方法 在前面几个章节中我们经常使用到System.out.println(),那么它是 ...

研磨设计模式之工厂方法模式(Factory Method)-模式讲解1

3.1 认识工厂方法模式(1)模式的功能 工厂方法的主要功能是让父类在不知道具体实现的情况下,完成自 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本