java - 如何在 Class<?> 的对象上执行方法

标签 java class reflection

我想知道是否可以在运行时在类的对象上执行类中的方法?

首先:我有返回一个类的方法:

public static Class<?> getClassById(Long id) throws ClassNotFoundException {
    if(d.id == 1L) {
        return First.class;
    } else if(d.id ==2L) {
        return Second.class;
    } else if(d.id ==3L) {
        return Third.class;
    } else {
        throw new ClassNotFoundException();
    }
}

第二:我执行它的方式:

Index.GetClassById(1) 应该返回我的类。现在我想从该类执行方法 myMethod() 。顺便说一句,(First、Second、Third) 的每个类都有这个 myMethod() 方法。

请帮忙。

最佳答案

Class 对象是代表您的类的类型的实例。这意味着 First.class.equals(new First()) 将始终返回 false。

您想要的是基于您的类创建一个对象,并在该类上调用您的方法 myMethod(),假设您的类(第一、第二、第三)有一个默认构造函数:

Class clazz = Index.getClassById(1);
First first = (First)clazz.newInstance();
first.myMethod();

这种方法的缺点是您必须显式地转换对象。

为了巧妙地中继工作,您应该定义一个定义 myMethod() 的接口(interface):

public interface MyInterface {
  void myMethod();
}
public class First implements MyInterface {
...
}
public class Second implements MyInterface {
...
}
public class Third implements MyInterface {
...
}

然后您可以将上面的方法定义为:

public static Class<MyInterface> getClassById(Long id) throws ClassNotFoundException {
    if(d.id == 1L) {
        return First.class;
    } else if(d.id ==2L) {
        return Second.class;
    } else if(d.id ==3L) {
        return Third.class;
    } else {
        throw new ClassNotFoundException();
    }
}

并这样调用它:

Class<MyInterface> clazz = Index.getClassById(1);
MyInterface instance = clazz.newInstance();
instance.myMethod();

关于java - 如何在 Class<?> 的对象上执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088791/

相关文章:

java - 如何使用 JBOSS 配置摆脱谷歌浏览器中过时的密码套件问题

vb.net - 无法从代码隐藏访问我的类(class)。类是App_Code文件夹

PHP - 两个类,彼此正确对话

java - Java的控制台输入大量数据

java - springboot 应用程序中的 Nio2Endpoint.Nio2SocketWrapper.getSslSupport 异常

java - 如果类是类型,那么它们可以保存什么类型的数据?

java - 查找 Java 中最具体的类

java - 字符串文字、实习和反射

处理数组的对象的 Java 字符串表示形式

java - 关注 CardLayout 中的 JTextField