在Java中消除类型擦除 [英] Getting around Type Erasure in Java

查看:193
本文介绍了在Java中消除类型擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我所从事的团队已经减少了我们为特定事物输入的代码量。在这种情况下,使用DisplayTag库显示列表的Spring网页。它完成的方式是使用泛型扩展 Controller 对象的类,然后是它应该工作的每个页面的子类。



此控制器显示 SystemErrorReport ,并将类型定义为 SystemErrorReportCommand 。 p>

  public class SystemErrorReportController extends 
GenericSearchAndSelectController< SystemErrorReportCommand> {

问题在于 SystemErrorReportCommand ,存在作为一个类型传递,需要在其构造函数中进行手动声明,如下所示:

  public SystemErrorReportCommand()
{
super(SystemErrorReport.class);
}

命令对象稍后传递给需要知道其显式类型的内容。没有在某处手动指定它,它会以 GenericCommand 的方式返回,这是我们的另一个类,因为 SystemErrorReportCommand 位在编译时间。



我对此并不感到激动,因为它似乎是我们可以进一步自动化以减少开发人员错误的方式。有没有一种更优雅的方式来做到这一点,或者我因为类型擦除而坚持使用它?

Javassist 做一些元编程。



它在Tapestry中用于此目的,请参阅 this 文章。


So, the group I work with has reduced the amount of code we have to type for certain things. In this case, a Spring web page that displays a list using the DisplayTag libraries. The way it's done is with a class using generics extending the Controller object, and then a subclass of that for each page it should work on.

This controller displays the SystemErrorReport, and defines the type to be the SystemErrorReportCommand.

public class SystemErrorReportController extends
    GenericSearchAndSelectController<SystemErrorReportCommand> {

The problem is that SystemErrorReportCommand, being passed as a type, needs to have a manual declaration of itself in its constructor, like so:

public SystemErrorReportCommand()
{
    super(SystemErrorReport.class);
}

The command object is later passed to something that needs to know its explicit type. Without specifying it manually somewhere, it comes back as GenericCommand, another class of ours, because the SystemErrorReportCommand bit is lost after compile time.

I'm not thrilled with that, because it seems like something we can farther automate to reduce developer error. Is there a more elegant way to do this, or am I stuck with this because of type erasure?

解决方案

Maybe you could use something like Javassist to do some meta-programming.

It's used in Tapestry for that purpose, see this article.

这篇关于在Java中消除类型擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆