Java泛型&反射

编程入门 行业动态 更新时间:2024-10-21 11:26:44
本文介绍了Java泛型&反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Class myClass = Class.forName(整数); SomethingSimple< myClass> OBJ;

其中SomethingSimple是一个简单的 泛型类:

class SomethingSimple< T> { T值; SomethingSimple(){} public void setT(T val) { value = val; } public T getT() {返回值; $ / code>

显然,上面的代码是不正确的,因为myClass是Class类型的对象,并且需要一个类。问题是如何实现这一点。我阅读了泛型反射的其他主题,但他们关心的是泛型类是如何知道类型的。

解决方案

使用Java中的泛型仅在编译时进行静态类型检查;类型检查后通用信息将被丢弃(请阅读类型擦除 ),所以在运行时, SomethingSimple< Foo> 实际上只是一个 SomethingSimple< Object> 。 $ b

当然,你不能对直到运行时才知道的类型进行补全时间类型检查。类型必须为编译器所知,这就是为什么你必须使用实际类型名称而不是 Class 变量作为泛型类型参数。

this probably is a basic question, but can I do something like this:

Class myClass = Class.forName("Integer"); SomethingSimple<myClass> obj;

Where SomethingSimple is a very simple generic class:

class SomethingSimple<T> { T value; SomethingSimple() {} public void setT(T val) { value = val; } public T getT() { return value; } }

Obviously, the code above is not correct, since myClass is an object of type Class, and a class is required. The question is how can this be achieved. I read the other topics about Generics Reflection, but they concerned how the generic class knows the type.

解决方案

Generics in Java are used only for static type checking at compile time; the generic information is discarded after type checking (read about type erasure) so a SomethingSimple<Foo> is effectively just a SomethingSimple<Object> at runtime.

Naturally, you can't do comple-time type checking on a type that isn't known until runtime. The type has to be known to the compiler, which is why you have to use an actual type name rather than a Class variable as the generic type parameter.

更多推荐

Java泛型&amp;反射

本文发布于:2023-11-16 23:57:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608043.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   Java   泛型   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!