java 用反射获取内部类构造方法

package com.zl.invoke;

import java.lang.reflect.Constructor;

public class A {

	public A() {

	}

	public A(String str) {

	}

	class Inner {
		private String name = "Inner";

		public Inner() {
		}

		public Inner(String na) {
			name = na;
		}
	}

	public static void main(String args[]) {

		Object obj = getObject("com.zl.invoke.A");
		System.out.println("obj: " + obj.toString());
		Object innerObj = getObjectFromInnerClass("com.zl.invoke.A$Inner");
		System.out.println("innerObj : " + innerObj.toString());
	}

	public static Object getObject(String className) {
		Object obj = null;
		try {
			Class c = Class.forName(className);
			if (c != null) {
				Constructor constructor = c
						.getDeclaredConstructor(new Class[] { String.class });
				if (constructor != null) {
					obj = constructor.newInstance("dlafjdf");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static Object getObjectFromInnerClass(String clsName) {
		Object obj = null;
		try {
			Class c = Class.forName(clsName);
			if (c != null) {
				Constructor constructor = c.getDeclaredConstructor(new Class[] {
						A.class, String.class });
				if (constructor != null) {
					obj = constructor.newInstance(new A(), "dlafjdf");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}

 

关键代码用红色字体标注:

  获取内部类构造方法时,需要将其外部类的类对象作为参数传进去

Constructor constructor = c.getDeclaredConstructor(new Class[] {

A.class, String.class });

同样实例化内部类时,也需要将外部类对象作为参数传进去

obj = constructor.newInstance(new A(), "dlafjdf");

你可能感兴趣的:(java,内部类,反射,反射获取内部类构造方法)