Java中的泛型和反射 [英] Generics and reflection in Java

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

问题描述

这可能是一个非常基本的问题,但是我对Java泛型确实是陌生的,并且我很难改变自己的思维方式与C#的处理方式,所以请耐心等待.

This is probably a very basic question, but I'm really new to generics in Java and I'm having a hard time altering my thought process from the way things are done in C#, so bear with me.

我正在尝试用Java构建通用存储库.我创建了一个IRepository接口,如下所示:

I'm trying to build a generic repository in Java. I've created an IRepository interface that looks like this:

public interface IRepository<T extends IEntity>

还有一个看起来像这样的Repository类:

And a Repository class that looks like this:

public class Repository<T extends IEntity> implements IRepository<T>

现在,从我的Repository类的构造函数中,我希望能够划分" T的确切类型.例如,如果我实例化了这样的存储库:

Now, from within the constructor of my Repository class, I'd like to be able to "divine" the exact type of T. For example, if I instantiated a repository like this:

IRepository<MyClass> repo = new Repository<MyClass>();

我想知道T实际上是MyClass.在C#中这是微不足道的,但是很明显,泛型在Java中是完全不同的野兽,我似乎找不到任何可以帮助我实现这一目标的东西.

I'd like to know that T is actually MyClass. This is trivial in C#, but obviously generics are a totally different beast in Java and I can't seem to find anything that would help me do this.

推荐答案

Java使用

Java uses type erasure, so the specific information is lost at runtime - you only know that this type is generic, not what's the specific argument you've supplied at compile time.

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

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