用反射实例化Java中的类

编程入门 行业动态 更新时间:2024-10-26 02:29:29
本文介绍了用反射实例化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

推荐答案

您需要将完全限定的类名称指定为 Class.forName(String) .

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中的类

本文发布于:2023-08-04 17:41:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298312.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   实例   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!