`
qq272936993
  • 浏览: 3012 次
社区版块
存档分类
最新评论

黑马程序员_反射之get/set工具类的实现

阅读更多

上一章节说了反射中学习到的知识,现在通过实践来写一个动态创建类,以及获取动态设值的方法

public class ReflectProUtils {
	
	
	/**
	 * 获取泛型中的类型
	 * 	 例如: List<String>   获取出的类型为 [String.class]
	 * 说明:
	 * 		需要获取泛型的,必须通过继承等方式重新构建一个新类,传递泛型的类型
	 * 		
	 * 可查考
	 * @throws ClassNotFoundException 
	 * 		@see BaseMapper
	 * */
	@SuppressWarnings("rawtypes")
	public static List<Class> getGenericsClass(Class thisClass) throws ClassNotFoundException{
		//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
		Type genType = thisClass.getGenericSuperclass();
		List<Class> list= new ArrayList<Class>();
        if (!(genType instanceof ParameterizedType)) { 
           list.add(Object.class);
           return list;  
        }  
        
        //返回表示此类型实际类型参数的Type对象的数组
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
        for(Type type : params){
        	list.add(
        			type2Class(type)	
        	);
        }
        return list;
	}
	
	/**
	 * Type类型转换为Class类型
	 * */
	public static Class type2Class(Type type) throws ClassNotFoundException{
		String clsStr = type.toString();
		String classStrPath = clsStr.substring(clsStr.indexOf(" ")+1 , clsStr.length());
		if(int.class.getName().equals(classStrPath))
			return int.class;
		else if(Constants.BYTE_NAME.equals(classStrPath))
			return byte.class;
		else if(Constants.SHORT_NAME.equals(classStrPath))
			return short.class;
		else if(Constants.LONG_NAME.equals(classStrPath))
			return long.class;
		else if(Constants.FLOAT_NAME.equals(classStrPath))
			return float.class;
		else if(Constants.DOUBLE_NAME.endsWith(classStrPath))
			return double.class;
		else if(Constants.CHAR_NAME.equals(classStrPath))
			return char.class;
		else if(Constants.BOOLEAN_NAME.equals(classStrPath))
			return boolean.class;
			
		return Class.forName(classStrPath);
	}
	
	/**
	 * 获取类中的所有字段,包括私有字段
	 * @param Class
	 * @return {@link Field}
	 * */
	@SuppressWarnings("rawtypes")
	public static Field[] getAllFields(Class cls){
		return cls.getDeclaredFields();
	}
	
	/**
	 * 只获取类中的公共方法,被public修饰的方法
	 * @param Class
	 * @return {@link Field}
	 * */
	@SuppressWarnings("rawtypes")
	public static Field[] getPublicFields(Class cls){
		return cls.getFields();
	}
	
	/**
	 * 获取当前类下的所有get/set方法
	 * @param Class
	 * @return {@link Map} 		<方法名,方法>
	 * */
	@SuppressWarnings("rawtypes")
	public static Map<String,Method> getAllGSMethods(Class cls){
		Map<String,Method> getSetMethodMap = new HashMap<String,Method>();
		Method[] methods = cls.getDeclaredMethods();
		for(Method method : methods){
			String name = method.getName();
			if(name.contains("get") || name.contains("set"))
				getSetMethodMap.put(name, method);
			
		}
		
		return getSetMethodMap;
	}
	
	/**
	 * 获取所有的方法
	 * @param cls
	 * @return {@link Method}
	 * */
	@SuppressWarnings("rawtypes")
	public static Method[] getAllMethods(Class cls){
		return cls.getDeclaredMethods();
	}
	
	/**
	 * 只获取公开的方法
	 * @param cls
	 * @return {@link Method}
	 * */
	@SuppressWarnings("rawtypes")
	public static Method[] getPublicMethods(Class cls){
		return cls.getMethods();
	}
	
	/**
	 * 为对象执行set方法,进行赋值
	 * 		set_T_Properties_value
	 * 
	 * @param fields 对象中的字段
	 * @param getSetMap get/set方法
	 * @param T	需要赋值的对象
	 * @param args 参数
	 * @throws Exception 
	 * */
	public static void setTProVal(Field field ,Object T,Object arg) throws Exception{
		String name = field.getName();
		
		try {
			Method method = T.getClass().getMethod( "set" + StringUtil.toUpperCaseFirstOne(name), arg.getClass());
			
			if(method != null){
				method.invoke(T, arg);
			}
		} catch (NoSuchMethodException e) {
			System.out.println("找不到对应参数类型的方法..请核对方法名和类型");
		}
	}
	
	public static <T>void setTProVal(T bean,Map<String,T> param) throws Exception{
		Field[] fields = getAllFields(bean.getClass());
		for(Field field : fields){
			field.setAccessible(true);
			String name = field.getName();
			Object val = param.get(name);
			if(val != null){
				setTProVal(field, bean, val);
			}
		}
	}
	
	/**
	 * 获取一个对象下面的字段对应的数据
	 * @param Field 字段
	 * @param obj	对象
	 * @throws Exception 
	 * */
	public static <T>Object getTProVal(Field field,T obj ) throws Exception{
		String name = field.getName();
		try {
			Method method = obj.getClass().getMethod("get"+StringUtil.toUpperCaseFirstOne(name));
			if(method != null){
				return method.invoke(obj, null);
			}
		} catch (NoSuchMethodException e) {
			System.out.println("找不到对应参数类型的方法..请核对方法名和类型");
		}
		return null;
	}
	
	
	/**
	 * 获取Field的类型
	 * @return 
	 * @throws ClassNotFoundException 
	 * */
	public static Class getFieldType(Field field) throws ClassNotFoundException{
		return type2Class(field.getType());
	}
	
	/**
	 * 判断某个类下是否有某个方法存在
	 * @param Class
	 * @param 方法名
	 * */
	public static boolean hasMethod(Class cls , String methodName){
		Map<String,Method> methodMap = getAllGSMethods(cls);
		if(methodMap == null) return false;
		else{
			Method method = methodMap.get(methodName);
			
			return method != null ? true :false;
		}
	}
	
	
	
	public static void main(String[] args) throws ClassNotFoundException {
		System.out.println(int.class.getName());
	}

	
}

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics