关rondom的是用!
求救!老师让随机产生一个类的对象,用数组保存!请教资深前辈,如何实现!!!!!
import java.util.Random; public class RandomClass { private String[] className = { "java.lang.String","java.util.ArrayList", "java.util.HashMap" ,"javax.swing.JFrame","java.lang.Thread"}; private static Random rand = new Random(); /** * @return 一个随机对象 * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * 注意:有些类是不能这样实例化的 */ public Object getRandomClass() throws ClassNotFoundException, IllegalAccessException, InstantiationException { String name = className[rand.nextInt(className.length)]; Object obj = Class.forName(name).newInstance(); System.out.println(name + " 被实例化"); return obj; } static public void main(String[] args)throws Exception{ Object[] o = new Object[4]; RandomClass rc = new RandomClass(); o[0] = rc.getRandomClass(); //随机获取一个对象放到数组保存…… } }