通过类名获取特定的类型数组
需求:参数为className,数组大小length,返回一个特定的类型的数组
耗费脑力一堆,但是答案相当的简单,代码如下
public static Object[] getArrayByClassName(String className, int length)throws NegativeArraySizeException, ClassNotFoundException {return (Object[]) Array.newInstance(Class.forName(className), length);}
public enum NoteMessage {A("A value"), B("B value");private final String value;public String getValue() {return value;}NoteMessage(String value) {this.value = value;}}
String[] strs = new String[] { "A", "B" };Object[] param1 = getArrayByClassName("NoteMessage", strs.length);Object[] param2 = new Object[strs.length];for (int i = 0; i < strs.length; i++) { param1[i] = getFieldObject(Class.forName("NoteMessage",strs[i]); param2[i] = getFieldObject(Class.forName("NoteMessage",strs[i]);}System.out.println(param1.getClass().getName());System.out.println(param2.getClass().getName());
public static Object getFieldObject(Object obj, String fieldName) throws SecurityException,NoSuchFieldException, IllegalArgumentException, IllegalAccessException,NoSuchMethodException, ClassNotFoundException {Field field = obj.getClass().getDeclaredField(fieldName);field.setAccessible(true);return field.get(obj);}