java反射机制-通过非默认构造器创建对象

今天研究了下java反射机制,并利用反射机制,通过非默认构造器创建对象,代码如下:

public class Toy {
	  // Comment out the following default constructor
	  // to see NoSuchMethodError from (*1*)
	 public Toy() {}
	 public Toy(int i) {}
	 public Toy(String s) {System.out.println("Toy(String s)");}
}
public class ToyTest {

	public static void main(String[] args) {
		Class c = null;
		Constructor con = null;
		Toy toy = null;
		try {
			c = Class.forName("typeinfo.toys.Toy");
			try {
                    //获取String类型构造器:
				con = c.getConstructor(String.class);
				System.out.println(con);

                    //传入“” 作为初始化参数
                                toy = (Toy) con.newInstance("");
				System.out.println(toy);
			}
			catch (NoSuchMethodException e) {}
			catch (IllegalArgumentException e) {}
			catch (InstantiationException e) {}
			catch (IllegalAccessException e) {}
			catch (InvocationTargetException e) {}

		}
		catch (ClassNotFoundException e) {
			print("Can't find FancyToy");
			System.exit(1);
		}
		catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(java,C++,c,C#)