Reputation: 2409
I have a
Vector<Class> v = new Vector<Class>();
a.addElement(HashMap.class);
....
How would I create an object out of i-element of the vector?
Upvotes: 1
Views: 144
Reputation: 1
Maybe this will help you understand the vector class
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());
Upvotes: 0
Reputation: 43504
If you do not have a default constructor you can use:
Object o = vector.get(i).getConstructor(parameterClazzes).newInstance(parameters);
else
Object o = vector.get(i).newInstance();
which takes the default constructor and creates your object
Example:
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);
}
Upvotes: 1
Reputation: 533492
Do you mean?
Class clazz = vector.get(i);
Object object = clazz.newInstance();
BTW: I wouldn't use Vector unless you have to as it is a legacy class replaced by List in Java 1.2 (1998)
Upvotes: 5