---
title: "使用Class创建带参数实例"
author: "conkeyn"
date: "2012-12-19T20:43:11Z"
tags: []
categories: ["编程语言"]
slug: "class"
draft: false
lastmod: "2012-12-19T20:45:09Z"
id: 1750631
url: "https://conkeyn.iteye.com/blog/1750631"
---

[http://stackoverflow.com/questions/1268817/create-new-class-from-a-variable-in-java](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.