hardcore java 学习5 反射

反射有很强大的能力。可以对一个未知的类调用其中的方法。就好象是从镜子里看人,而不是直观的进行。

现在很多优秀的框架、语言都借助反射的力量。

对未知类的方法调用:

/*
 *     file: MethodInfoDemo.java
 *  package: oreilly.hcj.reflection
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */

package oreilly.hcj.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import oreilly.hcj.bankdata.Gender;
import oreilly.hcj.bankdata.Person;

/**  
 * Demonstrates how to get simple method information.
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.3 $
 */
public class MethodInfoDemo {
	/** 
	 * __UNDOCUMENTED__
	 *
	 * @param obj __UNDOCUMENTED__
	 *
	 * @throws IllegalAccessException __UNDOCUMENTED__
	 * @throws InvocationTargetException __UNDOCUMENTED__
	 */
	public static void emptyStrings(final Object obj)
	    throws IllegalAccessException, InvocationTargetException {
		final String PREFIX = "set";  //$NON-NLS-1$
		Method[] methods = obj.getClass()
			                  .getMethods();
		for (int idx = 0; idx < methods.length; idx++) {
			if (methods[idx].getName()
			                .startsWith(PREFIX)) {
				if (methods[idx].getParameterTypes()[0] == String.class) {
					methods[idx].invoke(obj, new Object[] { new String() });
				}
			}
		}
	}

	/** 
	 * Demo method.
	 *
	 * @param args Command line arguments.
	 */
	public static void main(final String[] args) {
		Person p = new Person();
		p.setFirstName("Robert");
		p.setLastName("Simmons");
		p.setGender(Gender.MALE);
		p.setTaxID("123abc456");

		printMethodInfo(p);

		try {
			System.out.println("==> " + p.getFirstName());
			emptyStrings(p);
			System.out.println("==> " + p.getFirstName());
		} catch (final Exception ex) {
			ex.printStackTrace();
		}
	}

	/** 
	 * __UNDOCUMENTED__
	 *
	 * @param obj __UNDOCUMENTED__
	 */
	public static void printMethodInfo(final Object obj) {
		Class type = obj.getClass();
		final Method[] methods = type.getMethods();
		for (int idx = 0; idx < methods.length; idx++) {
			System.out.println(methods[idx]);
		}
	}
}

/* ########## End of File ########## */

王海良@Chatopera 聊天机器人 机器学习 智能客服
Chatopera 联合创始人 & CEO,运营聊天机器人平台 https://bot.chatopera.com,让聊天机器人上线!2015年开始探索聊天机器人的商业应用,实现基于自然语言交互的流程引擎、语音识别、自然语言理解,2018年出版《智能问答与深度学习》一书。