用反射实例化Java中的类 [英] Instantiating a class in Java with reflection

查看:47
本文介绍了用反射实例化Java中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一种方法,该方法将基于给定的接口实例化一个类.目前,我正在尝试根据类名称实例化一个类,但我一直在获取 ClassNotFoundException .

I am trying to create a method that will instantiate a class based on a given interface. At the moment I am trying to instantiate a class based on a class name but I keep getting ClassNotFoundException.

有人可以告诉我我在做什么错吗?

Can anyone tell me what I am doing wrong?

public class Message implements IExample{
    @Override
    public String showMessage() {
        return "merge";
    }
}

public static void main(String[] args) throws Exception{
    Object mess = Class.forName("Message").newInstance();
}

编辑

我尝试过:

Object mess = Class.forName("com.MyExample.Message").newInstance();
Object mess = Class.forName("Project.MyExample.Message").newInstance();
Object mess = Class.forName("MyExample.Message").newInstance();

他们都抛出 ClassNotFoundException 和一个窗口,该窗口带有一个让我浏览文档的按钮("Edit Source Lookup Path .."),告诉我找不到源".

They all throw ClassNotFoundException and a window which tells me "Source Not Found" with a button (Edit Source Lookup Path..) that let's me browse documents.

主类和 Message 类都在一个名为"Project"的项目和一个名为 MyExample

Both the main class and Message classes are in a project called "Project" and a package called MyExample

推荐答案

您需要将完全限定的类名称指定为

You need to specify the fully qualified class name to Class.forName(String).

参数: className所需类的完全限定名称.

Parameters: className the fully qualified name of the desired class.

如果 Message 位于程序包 com.package 中,则为 com.package.Message .

If Message is in package com.package, that would be com.package.Message.

Object mess = Class.forName("com.package.Message").newInstance();

启动应用程序时,该类必须位于类路径上.

That class must be on the classpath when launching the application.

这篇关于用反射实例化Java中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆