首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何动态生成新实例的方法调用类的Java反射?

如何动态生成新实例的方法调用类的Java反射?
EN

Stack Overflow用户
提问于 2019-01-22 14:03:10
回答 2查看 120关注 0票数 1

我有两个java类(Child1.java and Child2.java),它是从一个公共类(Parent.java)扩展而来的。我有另一个公共类(Common.java),它可以从两个子类中调用。我从Thread.currentThread().getStackTrace()获取调用者类名,并通过Java Reflection创建类实例。然后,我将从该类创建一个新的实例对象。因此,该方法的返回类型为Object

尽管我现在正在返回一个对象,但我需要以这样一种方式编写commonMethod():被调用的类的新实例应该是动态返回的。

代码语言:javascript
运行
复制
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();
}

任何帮助都将不胜感激

EN

回答 2

Stack Overflow用户

发布于 2019-01-22 14:26:22

试试这个:

代码语言:javascript
运行
复制
public Parent commonMethod() {
   // blah blah..
}
代码语言:javascript
运行
复制
    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();
        }
    }

你的结构不好。

但我认为这是有原因的。祝好运。

票数 0
EN

Stack Overflow用户

发布于 2019-01-22 14:29:35

这是你想要的吗?

代码语言:javascript
运行
复制
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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54302138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档