【问题标题】:Generic type, cast to method,field泛型类型,转换为方法,字段
【发布时间】:2021-03-11 03:39:12
【问题描述】:

我有这门课

class GameLoaderClass<V> {

V classValue = null;

Class<?> aClass;

ClassType classType;

public GameLoaderClass(ClassType classType, Class<?> aClass) {
    this.classType = classType;
    this.aClass = aClass;
}

public V getClassType(String name) {
    if (this.classType == ClassType.FIELD) {
        return this.classValue = aClass.getDeclaredField(name);
    } else
        return this.classValue = aClass.getMethod(name);

}

但我收到以下错误..

所需类型:C 提供:方法

有什么办法解决吗,谢谢

【问题讨论】:

  • 定义类class GameLoaderClass&lt;V extends java.lang.reflect.Member&gt;并使用类型转换return this.classValue = (V)aClass.getMethod(name);
  • @onkarruikar 是的,铸造它有效,但不安全,我想知道是否有没有铸造的方法
  • @Mekdbd 您希望将Method 对象分配给classValue,还是希望将classValue 分配给名为name 的方法返回的值?
  • @GauthamM 是的,我希望将方法对象分配给 classValue,但对象也可以是字段,我只想将值作为通用返回而不进行强制转换。
  • 您必须向编译器保证您将为变量分配一个可赋值的值。因此需要演员阵容。在方法 getClassType 上使用 @SuppressWarnings("unchecked")

标签: java generics lambda reflection


【解决方案1】:

我最好使用返回类型Object 而不是使用泛型。

public Member getClassType(String name) {
    if (this.classType == ClassType.FIELD) {
        return aClass.getDeclaredField(name);
    } 
    return aClass.getMethod(name);
}

在你调用方法的地方你可以做

Member obj = loader.getClassType("someName");
if(o instance of Field) {
    Field f = (Field) obj;
    // do the rest
} else /* Assuming Field or Method are the possible types of returned objects */ {
    Method m = (Method) obj;
    // do the rest
}

编辑:根据@Onkar 的评论,最好返回Member 类型的对象而不是Object,因为MethodField 都实现了Member

【讨论】:

  • java.lang.reflect.Member 会是比 Object 更好的选择
  • @onkarruikar 是的,这是一个很好的信息。我已经更新了
  • @onkarruikar 是的,这是一个很好的解决方案,但我想使用泛型,所以我可以使用这种方式 Method method = new GameLoaderClass().getClassType(ClassType.Method);
  • @Mekdbd 你还可以这样做吗? Method method = (Method) new GameLoaderClass(ClassType.Method, SomeClass.class).getClassType("someName");
  • @GauthamM 我想使用泛型而不进行强制转换
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多