New instance of class based on argument

后端 未结 4 427
时光说笑
时光说笑 2021-01-26 15:23

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

4条回答
  •  醉梦人生
    2021-01-26 15:45

    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.

提交回复
热议问题