ITeye博客

使用Class创建带参数实例

conkeyn · 2012-12-19 20:43 · 编程语言 · Markdown

http://stackoverflow.com/questions/1268817/create-new-class-from-a-variable-in-java

Consider I have a class:

com.crossedstreams.thingy.Foo

com.crossedstreams.thingy.Foo

 

Which has a constructor with signature:

Foo(String a, String b);

 

I would instantiate the class based on these two facts as follows:

// Load the Class. Must use fully qualified name here!
Class clazz = Class.forName("com.crossedstreams.thingy.Foo");

// I need an array as follows to describe the signature
Class[] parameters = new Class[] {String.class, String.class};

// Now I can get a reference to the right constructor
Constructor constructor = clazz.getConstructor(parameters);

// And I can use that Constructor to instantiate the class
Object o = constructor.newInstance(new Object[] {"one", "two"});

// To prove it's really there...
System.out.println(o);

 Output:

com.crossedstreams.thingy.Foo@20cf2c80

 

There's plenty of resources out there which go into more detail about this, and you should be aware that you're introducing a dependency that the compiler can't check for you - if you misspell the class name or anything, it will fail at runtime. Also, there's quite a few different types of Exception that might be throws during this process. It's a very powerful technique though.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。