Java 反射、类对象
我的目标是在命令行中读入我希望观察其信息的类的名称。当我在运行前知道类名时,就没有问题了。我似乎无法管理的是如何根据字符串输入创建类对象。
public class Tester {
static void methodInfo2(Object obj) throws ClassNotFoundException {
//some stuff
System.out.print("Test!");
}
public static void main (String args[]) throws ClassNotFoundException{
String className = args[0];
System.out.println("Class: "+className);
//myclass2 mc = new myclass2();
//Class c = mc.getClass();
Class argClass = Class.forName(className);
try {
methodInfo2(argClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
main 方法中的 2 行注释显示了我过去在编译之前知道类名时所做的操作。以下未注释的行显示了我认为应该有效的内容,但我收到了 ClassNotFoundException。该类确实存在,所以我不确定我遇到了什么问题。
My objective is to read in to the command line the name of a Class I wish to observe info on. When I know the class name before runtime, I have no issue. What I can't seem to manage is how to create a class object based on a string input.
public class Tester {
static void methodInfo2(Object obj) throws ClassNotFoundException {
//some stuff
System.out.print("Test!");
}
public static void main (String args[]) throws ClassNotFoundException{
String className = args[0];
System.out.println("Class: "+className);
//myclass2 mc = new myclass2();
//Class c = mc.getClass();
Class argClass = Class.forName(className);
try {
methodInfo2(argClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
The 2 commented out lines in the main method show what I have done in the past when I know the class name before I compile. The following uncommented line shows what I thought should work, but I receive a ClassNotFoundException. The class certainly exists so I'm not sure what problem I'm having.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个建议:
"java.lang.Thread"
而不仅仅是"Thread"
)。Two suggestions:
"java.lang.Thread"
and not just"Thread"
).Class.forName
是在运行时按名称加载类的正确方法。要么你的论点是错误的,要么你的类不在类路径中。
Class.forName
is the right way to load a class by name at runtime.Either your argument is wrong or your class isn't in the classpath.