我门先来定义一个接口:
package test;
public interface Shape {
public void draw();
}
接着我们在定义2个实现类
package test;
public class Circle implements shape {
public void draw() {
System.out.println(" circle draw");
}
}
package test;
public class Rectangle implements shape {
public void draw() {
System.out.println("rectangle draw");
}
}好,准备工作已经做好了,让我们开始吧.
package test;public MyTest{ public static void main(String args[]){
try{
String strConfigInfo=getConfigInfo();//getCofingInfo();是你的配置信息来源.可以是从
Class cls = Class.forName(strConfigInfo); //文件中读取,也可以来自注册表.
Shape shp = (Shape)cls.newInstance();
shp.draw();
}catch(Exception e){
e.printStackTrace();
}//end try_catch
}//end main
}//end MyTest说明:1,如果你现在写了个Shape的实现类MyShape,你只要修改一下配置信息,使getConfingInfo()取的信息是你的类的包路径(包含包名在内的类名,如java.io.FileWriter),那么shp.draw();将会调用你所写类中的draw()方法了. 2, 如果您要写插件,这将将是非常有用的技术.(比c++/delphi 中的动态连接库要方便多了.)
问题是:
那如果你要动态加载的类的构造器中有参数怎么办??
package test;
public interface Shape {
public void draw();
}
接着我们在定义2个实现类
package test;
public class Circle implements shape {
public void draw() {
System.out.println(" circle draw");
}
}
package test;
public class Rectangle implements shape {
public void draw() {
System.out.println("rectangle draw");
}
}好,准备工作已经做好了,让我们开始吧.
package test;public MyTest{ public static void main(String args[]){
try{
String strConfigInfo=getConfigInfo();//getCofingInfo();是你的配置信息来源.可以是从
Class cls = Class.forName(strConfigInfo); //文件中读取,也可以来自注册表.
Shape shp = (Shape)cls.newInstance();
shp.draw();
}catch(Exception e){
e.printStackTrace();
}//end try_catch
}//end main
}//end MyTest说明:1,如果你现在写了个Shape的实现类MyShape,你只要修改一下配置信息,使getConfingInfo()取的信息是你的类的包路径(包含包名在内的类名,如java.io.FileWriter),那么shp.draw();将会调用你所写类中的draw()方法了. 2, 如果您要写插件,这将将是非常有用的技术.(比c++/delphi 中的动态连接库要方便多了.)
问题是:
那如果你要动态加载的类的构造器中有参数怎么办??
解决方案 »
- 与pentaho系统的整合问题,急...
- javascript(jquery)如何与Struts2(Action)交互
- 初学ibatis,编译出错看不懂
- 主页 Application 加载统计数据问题
- 求Google App Engine JDO 多对多关系的例子
- Java开源门户系统Liferay 、JetSpeed 是什么,知道的进
- myeclipse配置ssh工程classpath的问题!
- csv 读取
- 怎么配置JBOSS 4.0啊
- 我用weblogic连接sql,通过测试,connection successfully,但是当我在程序中引用时老是不行
- 使用Struts,但不使用他的标签,是否可行?
- 北京地区招聘信息!!!!!!
问问题的话::java.lang.reflect.Constructor
扫盲的话::GZ
Class m_classdialog = java.lang.Class.forName("javax.swing.JDialog");
java.lang.reflect.Constructor cons = m_classdialog.getConstructor(new Class[] { Container.class });
Object m_objectdialog = cons.newInstance(new Object[] { parentContainer});
JDialog myDialog = (JDialog) m_objectdialog;