gpt4 book ai didi

java - 创建未知类型的数组

转载 作者:行者123 更新时间:2023-12-01 13:45:17 25 4
gpt4 key购买 nike

我有一个对象,我必须验证问题的值,对象的一些属性是自定义对象的数组。这样它就会涉及到数组的各个元素的一些无聊。为每个元素执行 getter,例如:

AttribGrp[] x =  Object.getAttribGrp()
x[i].getSomeValue()

这是我需要到达的。我已经使用带有列表的 Enum 提取了数据
属性如下。
public String getAttribValueAsString(MethodEnum attribName) 
{
String attribValue = null;
Object value = getAttrib(attribName.toString());

if (value != null)
attribValue = value.toString();

return attribValue;
}

调用:
    private Object invoke(String methodName, Object newValue)
{
Object value = null;
try
{
methodInvoker.setTargetMethod(methodName);

if (newValue != null)
methodInvoker.setArguments(new Object[]{newValue});
else
methodInvoker.setArguments(new Object[]{});

methodInvoker.prepare();
value = methodInvoker.invoke();
}
catch (ClassNotFoundException e)
{
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
}
catch (NoSuchMethodException e)
{
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
}
catch (InvocationTargetException e)
{
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
}
catch (IllegalAccessException e)
{
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
}
return value;
}

我将使用许多不同类型和数组中不同值的数组。我想创建一个方法如下。
    public Object getAttribArray(RIORepeatingGrpEnum repeatingGrp)
{
repeatingGrp[] grp = null;
Object grpVal = getAttrib(repeatingGrp.toString());
if(grp != null)
grp = (repeatingGrp[]) grpVal;

return grp;
}

这给了我多个主要与 repeatingGrp[] 有关的错误。数组类型应该与枚举同名。是否可以创建这样的方法来创建未定义类型的数组?

最佳答案

如果您想拥有未知类型的数组,请使用泛型:

 public <T> T[] getAttribArray(Class<T> repeatingGrpClass)
{
//get the attribute based on the class (which you might get based on the enum for example)
return (T[]) getAttrib( repeatingGrpClass.getName() ); //note that you might want to use the class object instead of its name here
}

关于java - 创建未知类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63156549/

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