开发者

How to create an object out of Vector<Class>?

开发者 https://www.devze.com 2023-03-09 16:31 出处:网络
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?Do you mean?

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?


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)


You could use newInstance:

v.get(i).newInstance()


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);
}


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());
0

精彩评论

暂无评论...
验证码 换一张
取 消