Instantiating a class in Java with reflection

╄→尐↘猪︶ㄣ 提交于 2021-02-17 02:04:10

问题


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();
}

EDIT

I have tried :

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

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.

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


回答1:


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

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

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.




回答2:


If your Message class is in a package, you need to specify the full name, such as edu.myschool.mypackage.Message.




回答3:


You need to provide the fully qualified name of the Class. If Messageis in package x.y then you have to provide x.y.Message.

Object mess = Class.forName("x.y.Message").newInstance();



回答4:


The class name shouldn't include the ProjectName, just the package name structure that is defined in your src folder.

If you are using Eclipse, make sure you defined the src folder correctly in your project. Here is how you can change the src folder for your app (if needed).

the Structure should be something like this:

Project
 |
 +-src
 | |
 | +-com
 |   |  
 |   +-MyExample
 |     |
 |     +-MyClass
 +-build

In this case, you should be able to say

Class.forName("com.MyExample.MyClass").newInstance();

It's very important how your structure in the src folder is defined and make sure you have the right src folder defined in your IDE project settings.



来源:https://stackoverflow.com/questions/18469948/instantiating-a-class-in-java-with-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!