Wil*_*ill 5 java arrays generics
我有一个对象,我必须验证问题的值,对象的一些属性是自定义对象的数组.这将涉及到一些无聊的阵列的各个元素.为每个元素执行getter,例如:
AttribGrp[] x = Object.getAttribGrp()
x[i].getSomeValue()
Run Code Online (Sandbox Code Playgroud)
我需要这样做.我已经使用带有属性列表的Enum提取数据.按以下方式.
public String getAttribValueAsString(MethodEnum attribName)
{
String attribValue = null;
Object value = getAttrib(attribName.toString());
if (value != null)
attribValue = value.toString();
return attribValue;
}
Run Code Online (Sandbox Code Playgroud)
电话:
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;
}
Run Code Online (Sandbox Code Playgroud)
我将在阵列中使用许多不同类型和不同值的数组.我想创建一个方法如下.
public Object getAttribArray(RIORepeatingGrpEnum repeatingGrp)
{
repeatingGrp[] grp = null;
Object grpVal = getAttrib(repeatingGrp.toString());
if(grp != null)
grp = (repeatingGrp[]) grpVal;
return grp;
}
Run Code Online (Sandbox Code Playgroud)
这给了我多个主要与repeatGrp []有关的错误.数组类型应与枚举名称相同.是否有可能创建一个这样的方法来创建一个未定义类型的数组?
如果您想拥有未知类型的数组,请使用泛型:
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
}
Run Code Online (Sandbox Code Playgroud)