Groovy的静态泛型类型 [英] Groovy static generic type

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

问题描述

我一直在玩弄赞成的ActiveRecord就像Java的实体摆脱的DAO,但仿制药会不会让我有我想要的全部功能(如静态的发现者)。不知怎的,Groovy的做法,但我很困惑为什么。鉴于以下内容:

I've been playing around with getting rid of DAOs in favor of ActiveRecord like entities in Java, but generics won't allow me to have the full functionality that I want (like static finders). Somehow Groovy does, but I'm confused why. Given the following:

class ActiveRecord<T> {
   static Class<T> genericType;
   ActiveRecord() {
     genericType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
   }
   static T find(Serializable id) { return EntityManagerHolder.find(genericType, id); }
   void save() { EntityManagerHolder.persist(this); }
}

@Entity @Table(name="TEST")
class FakeTable extends ActiveRecord<FakeTable> {
   @Id @GeneratedValue(strategy = GenerationType.AUTO)
   Long id;
   String status;
   String type;
   static void main(args) {
      FakeTable t = new FakeTable();
      t.status = "TESTING";
      t.save();
      println FakeTable.find(t.id);
   }
}

这code工作(与JPA东西,这除外),但我不知道为什么我能申报

This code works (with the JPA stuff that's excluded), but I'm not sure why I'm able to declare

static Class<T> genericType;

该编译器做一些神奇实际的Java类编译过吗?也许Groovy编译器与实际的类名称替换T在生成的Java类?

Does the compiler do some magic before the actual Java class is compiled? Maybe the groovy compiler is replacing T with the actual class name in the generated Java class?

在严格的Java,我可以访问从find方法返回类型和类声明泛型类型,但都被擦除为对象。这是很有意义的,和Groovy做同样的,但在Java,上面的行的错误用的消息类似于'不能引用非静态T'

In strictly Java, I can access the generic type from the find method return type and the class declaration, but both are erased to Object. That makes sense, and Groovy does the same, but in Java, the above line errors out with a message similar to 'Cannot reference non-static T'.

推荐答案

Groovy不是静态类型。我想你会发现它删除的T在编译的时候,甚至不打扰制定出它不是在范围;它只是无关Groovy的。

Groovy is not statically typed. I think you'll find it erases the T at compile time, and doesn't even bother to work out that it's not in scope; it's just irrelevant to Groovy.

这篇关于Groovy的静态泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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