雖然自己有保留範例,但難保不會遺失資料,而且記性變差,知道有Reflection可以運用,但都需要上網查詢,還是把以前做過的Sample貼上來,要回顧資料時就不難了。以下分別Demo ClassLoader、Constructor與Invoke的功能:
Noname1.java Demo用的Class
public class Noname1
{
public Noname1() {
}
{
public Noname1() {
}
public Noname1(String it, int me) { // Constructor用
System.out.println(it + "," + me);
}
System.out.println(it + "," + me);
}
public boolean exec(String it, int me) { // invoke用
System.out.println(it + "," + me);
return true;
}
System.out.println(it + "," + me);
return true;
}
}
TestClassLoader.java 執行期指定路徑載入Noname1,並invoke其功能
import java.lang.reflect.*;
import java.net.*;
class TestClassLoader
{
public static void main(String[] args) throws Exception
{
// URL[] us = {new URL("file:/C:/My/SampleCode/InvokeDemo/classes/")};
// ClassLoader loader = new URLClassLoader(us);
// Class c = loader.loadClass("Noname1");
Class c = (new URLClassLoader(new URL[]{new URL("file:/C:/My/SampleCode/InvokeDemo/classes/")})).loadClass("Noname1");
Object ob = c.newInstance();
Method m=c.getMethod("exec",new Class[]{Class.forName("java.lang.String"), Integer.TYPE});
Object it = m.invoke(ob,new Object[]{"Hello!", new Integer(100)});
if (it instanceof Boolean) {
System.out.println("yes!!");
}
System.out.println("it==>" + it);
}
import java.net.*;
class TestClassLoader
{
public static void main(String[] args) throws Exception
{
// URL[] us = {new URL("file:/C:/My/SampleCode/InvokeDemo/classes/")};
// ClassLoader loader = new URLClassLoader(us);
// Class c = loader.loadClass("Noname1");
Class c = (new URLClassLoader(new URL[]{new URL("file:/C:/My/SampleCode/InvokeDemo/classes/")})).loadClass("Noname1");
Object ob = c.newInstance();
Method m=c.getMethod("exec",new Class[]{Class.forName("java.lang.String"), Integer.TYPE});
Object it = m.invoke(ob,new Object[]{"Hello!", new Integer(100)});
if (it instanceof Boolean) {
System.out.println("yes!!");
}
System.out.println("it==>" + it);
}
// 指定帶參數的constructor
Class[] params = new Class[2];
params[0] = String.class;
params[1] = Integer.TYPE;
Constructor constructor = c.getConstructor(params);
Object[] paramObjs = new Object[2];
paramObjs[0] = "caterpillar";
paramObjs[1] = new Integer(90);
Object obj = constructor.newInstance(paramObjs); // Trigger Constructor function
}
params[0] = String.class;
params[1] = Integer.TYPE;
Constructor constructor = c.getConstructor(params);
Object[] paramObjs = new Object[2];
paramObjs[0] = "caterpillar";
paramObjs[1] = new Integer(90);
Object obj = constructor.newInstance(paramObjs); // Trigger Constructor function
}
1.若Noname1 class在classpath上,基本上只需做Class c=Class.forName("Noname1");即可。
2.上述sample是Noname1 class不在classpath上,註解的三行等於下一行的動作。
3.若Noname1可在classpath找到,會以classpath為先優先載入,不會去指定的URL搜尋。
4.URL若指定目錄,最後一個字元需是斜線 / 。
全站熱搜
留言列表