I\'m trying to make a function that takes one of many classes that extends Foo
, and return a new instance of that object in its Class, not a new instance of F
Your function could be like this
public class NewInstanceTest {
public static Object getNewInstance(Foo fooObject){
java.lang.Class fooObjectClass = fooObject.getClass();
try {
return fooObjectClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
public static void main(java.lang.String[] args){
// This prints Foo
java.lang.System.out.println(getNewInstance(new Foo()).getClass().getName());
// This prints Foo1
java.lang.System.out.println(getNewInstance(new Foo1()).getClass().getName());
}
}
class Foo{
}
class Foo1 extends Foo{
}
Hope this helps.