当前位置: 技术问答>java相关
程序动态加载时怎样传递参数?
来源: 互联网 发布时间:2015-04-10
本文导语: 我在程序中用到java的动态加载,就是不知怎样把调用程序中的变量值传递到 被加载的程序中去? 例如: String parameters="my parameter"; try { Runnable runable = (Runnable)Class.forName (className).newInstance(); ...
我在程序中用到java的动态加载,就是不知怎样把调用程序中的变量值传递到
被加载的程序中去?
例如:
String parameters="my parameter";
try {
Runnable runable = (Runnable)Class.forName (className).newInstance();
Thread thread=new Thread(group,runable,className);
thread.start(); //启动程序
}catch(Exception e){}
如果要把parameters传递到runable 中去该怎么办?
被加载的程序中去?
例如:
String parameters="my parameter";
try {
Runnable runable = (Runnable)Class.forName (className).newInstance();
Thread thread=new Thread(group,runable,className);
thread.start(); //启动程序
}catch(Exception e){}
如果要把parameters传递到runable 中去该怎么办?
|
在runable(className)中定义一个类变量String getParam。在runable start()之前把parameters值赋给runable(className)中预先定义的变量getParam。
|
因为java中new线程的时候只是初始化线程类变量,线程真正运行的是在调用start()之后。
|
public static void factory(className,param) {
Class c = null;
try {
c = Class.forName(className);
Run r = (Run)c.newInstance();
r.initial(param);
return r;
}catch(Exception e) {
throw e;
}
}
Class c = null;
try {
c = Class.forName(className);
Run r = (Run)c.newInstance();
r.initial(param);
return r;
}catch(Exception e) {
throw e;
}
}
|
public static Run factory(className,param) throws Exception {
Class c = null;
try {
c = Class.forName(className);
Run r = (Run)c.newInstance();
r.initial(param);
return r;
}catch(Exception e) {
throw e;
}
}
Class c = null;
try {
c = Class.forName(className);
Run r = (Run)c.newInstance();
r.initial(param);
return r;
}catch(Exception e) {
throw e;
}
}
|
public className();
**
try
{
Class cls = Class.forName(className);
Class[] cs = new Class[1];
cs[1] = java.lang.String.class;
Constructor ctr = cls.getConstructor(cs);
Object obj = ctr.newInstance(param);
}catch(Exception e){}
**
try
{
Class cls = Class.forName(className);
Class[] cs = new Class[1];
cs[1] = java.lang.String.class;
Constructor ctr = cls.getConstructor(cs);
Object obj = ctr.newInstance(param);
}catch(Exception e){}