谢谢楼上的回答,但是我还有一点疑问,如何来用动态的对象名来对新生成的对象进行引用。 比如这样 MyClass 对象名 = new MyClass();这里的对象名,如何来根据一个参数来动态的确定?
通过重载其构造函数 myclass obj1 = new myclass(); 构造器 is myclass() myclass obj2 = new myclass(string str); 构造器 is myclass(string ..);或者用匿名内部类实现 myclass obj3 = (new myclass(){f(),d(),c()})
建议你使用BeanShell来解决你 的问题, 很方便 import bsh.Interpreter;Interpreter i = new Interpreter(); // Construct an interpreter i.set("foo", 5); // Set variables i.set("date", new Date() ); Date date = (Date)i.get("date"); // retrieve a variable// Eval a statement and get the result i.eval("bar = foo*10"); System.out.println( i.get("bar") );// Source an external script file i.source("somefile.bsh");
kindani,这个方法我知道,但是我不知道,如何实现对象名的动态命名
比如说 Class.forName(classname).newInstance(),这个会生成一个object对象,然后我要用一个赋值语句比如MyClass instancename = (MyClass)Class.forName(classname).newInstance(),这里的instancename该怎么样从传过来的参数中命名呢
Toy(){}
public Toy(int i){
System.out.println("Toy");
}
public String toString(){
return "haha";
}
}}
public class ToyTest{
public static void main(String[] args)throws Exception{
Constructor ctor = Toy.class.getConstructor(int.class);
Object[] b = new Object[] {2};
//Toy ts = ctor.newInstance(b);
System.out.println(ctor.newInstance(3));
}
}
你看一下应该就懂了,我用的是Toy的带参数的构造器来生成它的对象的,
你的的话,主要把int.class改成String.class,然后再稍微修改一下,应该就可以了.
你看一下下面这几个方法 !
• Constructor getConstructor(Class[] params) -- 获得使用特殊的参数类型的公共构造函数,
• Constructor[] getConstructors() -- 获得类的所有公共构造函数
• Constructor getDeclaredConstructor(Class[] params) -- 获得使用特定参数类型的构造函数(与接入级别无关)
• Constructor[] getDeclaredConstructors() -- 获得类的所有构造函数(与接入级别无关)
比如这样 MyClass 对象名 = new MyClass();这里的对象名,如何来根据一个参数来动态的确定?
myclass obj1 = new myclass(); 构造器 is myclass()
myclass obj2 = new myclass(string str); 构造器 is myclass(string ..);或者用匿名内部类实现
myclass obj3 = (new myclass(){f(),d(),c()})
Javascript 中eval()的功能。 这在当前JDK 5.0不可能。 JDK 6或许
会包含类似的功能,见JSR199
很方便
import bsh.Interpreter;Interpreter i = new Interpreter(); // Construct an interpreter
i.set("foo", 5); // Set variables
i.set("date", new Date() ); Date date = (Date)i.get("date"); // retrieve a variable// Eval a statement and get the result
i.eval("bar = foo*10");
System.out.println( i.get("bar") );// Source an external script file
i.source("somefile.bsh");