gpt4 book ai didi

java - 从通用类创建新的特定对象

转载 作者:行者123 更新时间:2023-11-30 03:31:21 25 4
gpt4 key购买 nike

好吧,我环顾四周,我想我可能做错了。我在大学里选修了 C++ 类(class),我喜欢修修补补,但我仍在学习 Java。

所以我使用 ListAdapter 来放置用户可以从中选择的不同 fragment 的列表,然后他们选择的 fragment 位于 ListAdapter 所在的位置。它只需要数组,没什么大不了的。

/**
* An array of POJOs used to hold the info about the fragments we'll be
* swapping between This should be inserted into an array adapter of some
* sort before being passed onto ListAdapter
*/
private static final FragmentDetails[] FRAGMENT_DETAILS = {
new FragmentDetails(R.string.action_extraInfo,
R.string.extraInfo_description,
ExtraInfoFragment.class),
new FragmentDetails(R.string.action_largeTach,
R.string.largeTach_description,
LargeTachFragment.class),
...
};
/**
* @author PyleC1
*
* A POJO that holds a class object and its resource info
*/
public static class FragmentDetails {
private final Class<? extends Fragment> fragmentClass;
private int titleId;
private int descriptionId;
/**
* @param titleId
* The resource ID of the string for the title
* @param descriptionId
* The resource ID of the string for the description
* @param fragmentClass
* The fragment's class associated with this list position
*/
FragmentDetails(int titleId, int descriptionId,
Class<? extends Fragment> fragmentClass) {
super();
this.titleId = titleId;
this.descriptionId = descriptionId;
this.fragmentClass = fragmentClass;
}

...
}

无论如何,我通过一个名为 CustomArrayAdapter 的简单获取/设置类来运行它,并在附加 fragment 时将其发送到 ListAdapter。

public void onAttach(Activity activity) {
super.onAttach(activity);

ListAdapter listAdapter = new CustomArrayAdapter(getActivity(),
FRAGMENT_DETAILS);
setListAdapter(listAdapter);

到目前为止一切顺利。当我尝试对 onListItemClick 监听器进行编程时,问题就出现了。我似乎找不到从类信息创建真实对象的方法。我环顾四周,发现 .getClass().newInstance() 函数应该与 new 大致相似,所以我尝试了这个。

public void onListItemClick(ListView l, View v, int position, long id) {
FragmentDetails details = (FragmentDetails) getListAdapter().getItem(position);

FragmentManager fragmentManager = ...
FragmentTransaction fragmentTransaction = ...

fragmentTransaction.add(R.id.fragment_container,
details.fragmentClass.newInstance());
}

这样做会在编译器中引发非法访问异常。我知道类似的东西在 C++ 中是可以接受的。也许是一个类指针?但这在 Java 中可能是完全错误的方式。也许不是类型安全的?

我唯一的其他想法是删除

Class<? extends Fragment> fragmentClass

来自数组的泛型,只使用一个 switch 语句(也许来自标题 id)来硬编码 fragment 事务,尽管这看起来有点不雅。如果你想启动新的 Activity ,它工作得很好,你可以像这样将通用类传递给 Intent :

Class<? extends Foo> bar = someFooClass.getClass();
new Intent(this, bar);

但是 fragment 不接受这个。

最佳答案

根据documentation :

IllegalAccessException - if the class or its nullary constructor is not accessible.

因此,如果您想使用反射实例化您的 fragment ,所有可能的类 <? extends Fragment>需要提供一个public无参数构造函数。

关于java - 从通用类创建新的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com