首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

经过类名获取特定的类型数组

2012-11-03 
通过类名获取特定的类型数组需求:参数为className,数组大小length,返回一个特定的类型的数组耗费脑力一堆,

通过类名获取特定的类型数组
需求:参数为className,数组大小length,返回一个特定的类型的数组

耗费脑力一堆,但是答案相当的简单,代码如下

public static Object[] getArrayByClassName(String className, int length)throws NegativeArraySizeException, ClassNotFoundException {return (Object[]) Array.newInstance(Class.forName(className), length);}


别看这个返回是Object[],你如果使用反射getClass().getName() 得到的就是你想要的数组类型,适用于枚举。

举个例子:
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());

getFieldObject方法如下
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);}


热点排行