JAVA problem哪位大侠讲讲java.lang.Class和java.lang.ClassLoader怎么用的?
我主要想用一个string表示的名字来调用同名的一个class,不知道上面两个class能否做到这点?即
string temp = "MyClass";
public class MyClass{
public static void testmethod(){
System.out.println("Test OK");
}
}
问题要求我如何把temp提交给java.lang.Class或java.lang.ClassLoader然后返回MyClass,这样就可以直接调用testmethod了。
如果您知道,请讲仔细点好吗?谢谢
Some points here:
1) You don't normally make direct use of ClassLoader, unless you wanna customize the security/access/initialization mechanism of the default class loaders provided.
2) To use java.lang.Class to load a class, simple do this:
try {
Class cls = Class.forName("MyClass");
Object obj = cls.newInstance();
} catch (....) {
}
//There is a long list of possible exceptions here. Check JDK API doc for the list.
2) To use java.lang.Class to load a class, simple do this:
try {
Class cls = Class.forName("MyClass");
Object obj = cls.newInstance();
} catch (....) {
}
//There is a long list of possible exceptions here. Check JDK API doc for the list.