在运行时获取通用类的类

编程入门 行业动态 更新时间:2024-10-10 11:29:58
本文介绍了在运行时获取通用类的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

public class GenericClass< T> { public Type getMyType() { //如何返回T的类型? $ b $ p $ b

到目前为止我尝试过的所有东西总是返回 Object 而不是使用的具体类型。

如果您确实需要这种类型,这是一种常用的(类型安全的)解决方法模式:

public class GenericClass< T> { private final Class< T>类型; public GenericClass(Class< T> type){ this.type = type; } public Class< T> getMyType(){ return this.type; } }

How can I achieve this?

public class GenericClass<T> { public Type getMyType() { //How do I return the type of T? } }

Everything I have tried so far always returns type Object rather than the specific type used.

解决方案

As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> { private final Class<T> type; public GenericClass(Class<T> type) { this.type = type; } public Class<T> getMyType() { return this.type; } }

更多推荐

在运行时获取通用类的类

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

发布评论

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

>www.elefans.com

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