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);
- Peter answered the first question very well.
- 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
精彩评论