java 用反射获取内部类构造方法_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java 用反射获取内部类构造方法

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

 2013/7/16 0:48:19  hold_on  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.zl.invoke;importjava.lang.reflect.Constructor;publicclassA{publicA(){}publicA(Stringstr){}classInner{privateStringname="Inner";publicInner(){}publicInner(Stringna){name=na;}}publicstaticvoidmain(Stringargs[]){Objectobj=getObject("com.zl
  • 标签:方法 构造 Java 反射
class="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");

发表评论
用户名: 匿名