2011-05-31 38 views

回答

5

你的意思是?

Class clazz = vector.get(i); 
Object object = clazz.newInstance(); 

BTW:我不會用向量,除非你有,因爲它是名單中的Java替代1.2(1998)

2

如果您沒有默認構造函數,您可以使用:

Object o = vector.get(i).getConstructor(parameterClazzes).newInstance(parameters); 

其他

Object o = vector.get(i).newInstance(); 

這需要默認的構造函數,並創建你的對象


例子:

public static void main(String args[]) throws Exception { 

    Integer i = Integer.class.getConstructor(Integer.TYPE).newInstance(17); 
    System.out.println(i); 

    String s = String.class.getConstructor(String.class).newInstance("Hello"); 
    System.out.println(s); 
} 
0

也許這將幫助你理解向量類

class Person{ 
private String name; 
private String lastname; 
public void setName(String name){this.name = name;} 
public void setLastname(String lastName){this.lastname = lastname;} 
public String getName(){return name;} 
public String getLastname(){ return lastname;} 
} 

Vector<Person> v = new Vector<Person>(10,2); 
Person objPerson = new Person(); 

objPerson.setName("Carl"); 
objPerson.setLastname("Jhonson"); 

v.addElement(objPerson); 

System.out.println("Name: "+v.elementAt(i).getName()); 
System.out.println("Lastname: "+v.elementAt(i).getLastname());