问题
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 Message
is 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