开发者

It's is possoble create objects from a Class passed as parameter?

I done a method that receive a class and a int. I want to know if is possible and how I do to create an object from the passed Class parameters.

public void createObject(Class clazz, int n){
    for(int i=0;i<n;i++){
        //new object from the clazz
    }
}

It's possible开发者_JAVA技巧 to do this? I will create te objects to run in threads.

How can I assure that the Class implements Callable?

EDIT: it's possible calling a Construcor with arguments?


Do you means like this?

if(Callable.class.isAssignableFrom(clazz)) {
    Callable obj = (Callable) clazz.newInstance();

} else if (MyAbstractClass.class.isAssignableFrom(clazz)) {
    MyAbstractClass obj = (MyAbstractClass) clazz.newInstance();

} else {
    throw new IllegalArgumentException(clazz+" not valid");
}

If you have a constructor which takes arguments you can do

Callable obj = (Callable) clazz.getConstructor(int.class).newInstance(10);


  1. Peter answered the first question very well.
  2. public void createObject(Class<? extends Callable> clazz, int n){


    if (!Callable.class.isAssignableFrom(clazz)) {
        // whatever error condition
    }
    Callable callable = (Callable) clazz.newInstance();


This method will help you check whether the passed class implements an interface/extends a class.


You can see more on this here ... http://download.oracle.com/javase/tutorial/reflect/class/classNew.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜