reflectionutils.java

来自「主要是对串口驱动的的一些控制源码!!! 在下载javacomm20-win32」· Java 代码 · 共 290 行

JAVA
290
字号
/**
 * $Log: ReflectionUtils.java,v $
 * Revision 1.1  2003/01/16 13:05:55  mwulff
 * initial version
 *
 * Revision 1.4  2003/01/13 12:44:53  mwulff
 * no message
 *
 * Revision 1.3  2003/01/11 18:01:28  willaxt
 * primitive type short not handled in findMember()
 *
 * Revision 1.2  2003/01/02 18:46:52  mwulff
 * no message
 *
 * Revision 1.1  2003/01/02 11:58:32  mwulff
 * no message
 *
 * Revision 1.1  2002/12/14 22:42:58  mwulff
 * no message
 *
 * Revision 1.1  2002/12/13 20:07:33  mwulff
 * no message
 *
 */
package de.fhm.jkf.utils.clsv;

import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author	marten wulff
 * 
 * * <br><br><center><table border="1" width="80%"><hr>
 * <strong><a href="http://jkf.sourceforge.net">The JKF Project</a></strong>
 * <p>
 * Copyright (C) 2002 by Marten Wulff
 * <p>
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * <p>
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * <p>
 * You should have received a copy of the <a href="http://www.gnu.org/copyleft/lesser.html">
 * GNU Lesser General Public License</a> along with this library; if not, write to
 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA  02111-1307  USA
 * <hr></table></center>
 */

public class ReflectionUtils {
	
	/**
	 * @param  args  an Object array
	 * @return  an array of Class objects representing the classes of the
	 * objects in the given Object array.  If args is null, a zero-length
	 * Class array is returned.  If an element in args is null, then
	 * Void.TYPE is the corresponding Class in the return array.
	 */
	private static Class[] getSignature(Object[] args) {
		Class[] argTypes = null;

		if (args != null) {
			argTypes = new Class[args.length];

			for (int i = 0; i < args.length; ++i)
				argTypes[i] =
					(args[i] == null) ? Void.TYPE : args[i].getClass();
		} else
			argTypes = new Class[0];

		return argTypes;
	}

	private static Member findMember(Object[] members, Class[] params) {
		
		Member candidateMember = null;
		Class[] candidateParams = null;
		
		// iterate over all members and compare their signature to the 
		// given params
		for(int i = 0; i < members.length; i++) {
			
			candidateMember = (Member)members[i];
			
			// get the parameter types of the member
			if(candidateMember instanceof Method) {
				candidateParams = ((Method)candidateMember).getParameterTypes();		
			}else if(candidateMember instanceof Constructor) {
				candidateParams = ((Constructor)candidateMember).getParameterTypes();		
			}
			
			if(paramsEquals(params, candidateParams)) {
				// we've found a matching member return it
				return candidateMember;
			} else {
				continue;
			}
			
		}
		
		// if we get here, we didn't found a matching member 
		return null;		
	}
	
	public static Constructor findConstructor(Class clazz, Object[] params) throws NoSuchMethodException {

		Constructor result = null;		
		Class[] signature = getSignature(params);
				
		// first do it normal way
		try{
			return clazz.getConstructor(signature);
		}catch(NoSuchMethodException ignored) {}
			
		result = (Constructor)findMember(clazz.getConstructors(), signature);
		
		if(result == null) {
			throw new NoSuchMethodException("No constructor found");
		}
		
		return result;
	}
	
	
	public static Method findMethod(Class clazz, String mName, Object[] params) throws NoSuchMethodException {
			
		Class[] signature = getSignature(params);
		boolean foundMethod = false;
		Method[] methods = null;
		ArrayList list = null;
		Method result = null;
				
		// first do it normal way
		try{
			return clazz.getMethod(mName, signature);
		}catch(NoSuchMethodException ignored) {}
		
		while(true) {	
			// get a list of all methods with the same name in this class
			methods = clazz.getDeclaredMethods();
			list = new ArrayList();
			for(int i = 0; i < methods.length; i++) {
				if(methods[i].getName().equals(mName)) {
					list.add(methods[i]);
				}
			}
		
			// search method if we find a method in this class matching
			// the given method name
			if(list.size() > 0) {
				result = (Method)findMember(list.toArray(), signature);
				if(result != null) {
					foundMethod = true;
				}
			}
			
			// go on with the super class if we haven found a method yet
			// and current class isn't Object
			if(!foundMethod && !clazz.equals(Object.class)) {
				clazz = clazz.getSuperclass();
			} else {
				
				// leave if we have already searched Object.class or if we
				// have found a method 
				break;
			}
		}
		
		// throw an exception if we can't find a method with the given name
		if(!foundMethod) {
			throw new NoSuchMethodException("No method found (" + mName + ")");
		}
				
		return result;
	}
	
	public static Method[] getGetters(Class clazz) {
		
		ArrayList tmp = new ArrayList();
		Method[] result = null;
		Method[] methods = clazz.getDeclaredMethods();		
		
		String methodName = null;
		for(int i = 0; i < methods.length; i++) {
			methodName = methods[i].getName();
			if(methodName.startsWith("get")) {
				tmp.add(methods[i]);
			}
		}
		
		Iterator it = tmp.iterator();
		result = new Method[tmp.size()];		
		
		int counter = 0;
		while(it.hasNext()) {
			result[counter++] = (Method)it.next();
		}
		
		return result;
	}
	
	public static Method[] getSetters(Class clazz) {
		
		ArrayList tmp = new ArrayList();
		Method[] result = null;
		Method[] methods = clazz.getDeclaredMethods();		
		
		String methodName = null;
		for(int i = 0; i < methods.length; i++) {
			methodName = methods[i].getName();
			if(methodName.startsWith("set")) {
				tmp.add(methods[i]);
			}
		}
		
		Iterator it = tmp.iterator();
		result = new Method[tmp.size()];		
		
		int counter = 0;
		while(it.hasNext()) {
			result[counter++] = (Method)it.next();
		}
		
		return result;
	
	}
	
	private static boolean paramsEquals(Class[] params, Class[] candidateParams) {
		
		Class callerParam = null;
		Class candidateParam = null;
		
		// first check if both arrays have the same length, that means both
		// methods have the same amount of parameters
		if(params.length != candidateParams.length) {
			return false;
		}
		
		for(int i = 0; i < params.length; i++) {
			callerParam = params[i];
			candidateParam = candidateParams[i];	
			
			// convert the given parameter to primitive types if 
			// the parameter of the candidate is a primitive
			if(candidateParam.isPrimitive()) {
				if(callerParam.equals(Integer.class)) {
					callerParam = Integer.TYPE;
				} else if(callerParam.equals(Long.class)) {
					callerParam = Long.TYPE;
				} else if(callerParam.equals(Double.class)) {
					callerParam = Double.TYPE;
				} else if(callerParam.equals(Float.class)) {
					callerParam = Float.TYPE;
				} else if(callerParam.equals(Byte.class)) {
					callerParam = Byte.TYPE;
				} else if(callerParam.equals(Character.class)) {
					callerParam = Character.TYPE;
				} else if(callerParam.equals(Boolean.class)) {
					callerParam = Boolean.TYPE;
				} else if(callerParam.equals(Short.class)) {
					callerParam = Short.TYPE;
				}
			}						

			// if only one parameter wrong return false			
			if(!callerParam.equals(candidateParam)) {
				return false;
			} else if(callerParam.equals(candidateParam) && i == (params.length - 1)) {
				// if all parameters are equal and there are no more parameters both
				// signatures are equal
				return true;
			} else {
				// there are still parameters to test for equality, but until now all
				// tested are equals, go on
				continue;
			}
		}
		
		return false;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?