思路:
可以使用集合來定義數(shù)組测蘑,利用反射獲取類中指定的方法绽左,
而Method類中的invoke()允許調(diào)用包裝在當前method對象中的方法
因此可以直接調(diào)用add方法添加字符串元素
invoke(Object obj, Object... args)
參數(shù):obj - 從中調(diào)用底層方法的對象
args - 用于方法調(diào)用的參數(shù)
返回:使用參數(shù) args在obj上指派該對象所表示方法的結(jié)果
代碼:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* 利用反射可以繞過一些編譯時的類型檢查
* 比如在integer數(shù)組中加入一個字符串
* @author: Joker
* @date: 2017年1月30日 下午8:15:22
*/
public class ReflectDemo
{
public static void main(String[] args)
{
// 創(chuàng)建類型為Interger的ArrayList集合
ArrayList<Integer> arrayList = new ArrayList<Integer>();
//add方法給list集合中添加元素
arrayList.add(101);
arrayList.add(100);
arrayList.add(102);
//獲取字節(jié)碼文件對象
Class arrayListClass = ArrayList.class;
try
{//利用getMethod(String name, Object obj)獲取ArrayList類中指定的add方法
Method method = arrayListClass.getMethod("add", Object.class);
//直接調(diào)用add方法添加字符串元素,返回add方法執(zhí)行后的結(jié)果
method.invoke(arrayList, "helloworld");
}
catch (NoSuchMethodException | SecurityException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
System.out.println("新集合為:" + arrayList);
}
}
控制臺輸出:
新集合為:[101, 100, 102, helloworld]