简体   繁体   中英

How to generate new instance of the method caller class dynamically Java Reflection?

I have 2 java classes (Child1.java and Child2.java) which extends from a common class (Parent.java) . I have another common class (Common.java) which can be called from both Child classes. I am getting the caller class name from the Thread.currentThread().getStackTrace() and crate the Class instance through Java Reflection . Then I am creating a new instance object from that class. Therefore the return type of the method is Object

Although I am returning an object at the moment, I need commonMethod() to be written in a such a way where the called class new instance should be returned dynamically.

public class Child1 extends Parent {

  public void method1()
  {
    new Common().commonMethod();
  }

}

public class Child2 extends Parent {

  public void method2()
  {
    new Common().commonMethod();
  }

}


public Object commonMethod() throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
  String className = Thread.currentThread().getStackTrace()[2].getClassName();
  Class clazz = Class.forName(className);

  return clazz.newInstance();
}

Any help would be appreciated

Try this:

public Parent commonMethod() {
   // blah blah..
}
    public class Child1 extends Parent {

        public void method1()
        {
            new Common() {
                @Override
                public Child1 commonMethod() {
                    return new Child1();
                }
            }.commonMethod();
        }

    }

    public class Child2 extends Parent {

        public void method2()
        {
            new Common() {
                @Override
                public Child2 commonMethod() {
                    return new Child2();
                }
            }.commonMethod();
        }
    }

Your structure is not good.
But I think there a reason. Good luck.

Is this what you want?

public <T extends Object>T commonMethod() throws ClassNotFoundException, InstantiationException, 
IllegalAccessException
{
  String className = Thread.currentThread().getStackTrace()[2].getClassName();
  Class clazz = Class.forName(className);

  return (T) clazz.newInstance();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM