简体   繁体   English

从泛型类型获取类对象

[英]Get class object from generic type

I want to simplify a project by removing useless classes. 我想通过删除无用的类来简化项目。 By useless classes I mean something like : 通过无用的类,我的意思是:

public class MainPage extends TileGridFragment<MainModel> {}

The whole logic of this class is implemented by TileGridFragment , and the data is provided by MainModel , which instance is accessed thanks to a singleton class. 该类的整个逻辑由TileGridFragment实现,数据由MainModel提供,由于使用了singleton类,因此可以访问该实例。

I want to defer the instanciation of such class to a later time, so I simply pass MainPage.class to my methods. 我想将此类的实例化推迟到以后,所以我只是将MainPage.class传递给我的方法。

As MainPage is equivalent to TileGridFragment<MainModel> , I would like to remove this class and instead use something like TileGridFragment<MainModel>.class instead. 因为MainPage等效于TileGridFragment<MainModel> ,所以我想删除此类,而改用TileGridFragment<MainModel>.class类的东西。

But this doesn't work and I'm out of idead. 但这是行不通的,我没想到。

I've also tried Class.forName , but its throws a ClassNotFoundException . 我也尝试过Class.forName ,但是它抛出ClassNotFoundException

Any idea ? 任何想法 ?

If the implementation of MainPage is actually {} , just pass TileGridFragment.class . 如果MainPage的实现实际上是{} ,则只需传递TileGridFragment.class The actual type parameters are irrelevant on runtime because they are removed by erasure . 实际类型参数与运行时无关,因为它们会被擦除删除

Also, because of erasure, you can cast the new TileGridFragment (with a raw type, as the result of TitleGridFragment.class.newInstance() ) to TitleGridFragment<MainModel> , and ther will be no collateral damages (other than a little warning from the compiler, that can be supressed). 另外,由于擦除的原因,您可以将新的TileGridFragment (具有原始类型,作为TitleGridFragment.class.newInstance()的结果) TitleGridFragment<MainModel>TitleGridFragment<MainModel> ,并且不会造成附带损害(除了来自编译器)。

You can't really, you might get some joy from reflection but I'm not sure exactly what you're trying to do. 您不能真正地从反射中得到一些快乐,但是我不确定您到底想做什么。

Try here: Get generic type of class at runtime 试试这里: 在运行时获取类的通用类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM