All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jfplugin.xsql.kit.ObjectKit Maven / Gradle / Ivy

The newest version!
package com.jfplugin.xsql.kit;

import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.jfplugin.xsql.exception.NoPropertyException;

public class ObjectKit {

	public static Object getProperty(Object bean, String key) {
		StringTokenizer tokenizer = new StringTokenizer(key, ".", false);
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();
			if(bean instanceof Map){
				bean = ((Map) bean).get(token);
			}else if (bean instanceof List){
				try {
					bean = ((List) bean).get(Integer.parseInt(key));
				} catch (Exception e) {
					throw new NoPropertyException(bean.getClass()+"中"+key+"属性不存在", e);
				}
			}else if (bean.getClass().isArray()){
				try {
					bean = getArrayItem(bean,Integer.parseInt(key));
				} catch (Exception e) {
					throw new NoPropertyException(bean.getClass()+"中"+key+"属性不存在", e);
				}
			}else{
				try {
					bean = Reflect.on(bean).field(token).get();
				} catch (Exception e1) {
					try {
						bean = Reflect.on(bean).call("get",token).get();
					} catch (Exception e2) {
						throw new NoPropertyException(bean.getClass()+"中"+key+"属性不存在", e2);
					}
				}
				
			}
			
		}
		return bean;
	}

	/**
	 * 获取数组中的一条
	 * @param o
	 * @param index
	 * @return
	 */
	private static Object getArrayItem(Object o , int index){
		Class type = o.getClass();
		if(type.getComponentType().isPrimitive()){
			
			if (type == int[].class)
			{
				return ((int[]) o)[index];
			}
			else if (type == long[].class)
			{
				return ((long[]) o)[index];
			}
			else if (type == short[].class)
			{
				return ((short[]) o)[index];
			}
			else if (type == double[].class)
			{
				return ((double[]) o)[index];
			}
			else if (type == float[].class)
			{
				return ((float[]) o)[index];
			}
			else if (type == char[].class)
			{
				return ((char[]) o)[index];
			}
			else if (type == byte[].class)
			{
				return ((byte[]) o)[index];
			}
			else if (type == boolean[].class)
			{
				return ((boolean[]) o)[index];
			}
			else
			{
				throw new RuntimeException("不支持数组");
			}
		}else{
			return ((Object[]) o)[index];
		}
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy