java 反射例子——模仿mybatis的简单实现

对于反射的一些基础知识这里不再说明,网上有很多的文章了,可参考这篇文章https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html

这里主要通过一个简单的例子说明反射的应用。该例子主要是模仿mybatis的一个简单的实现,该例子可能有很多问题,但只是为了说明反射的一个具体应用。

package com.ctcf._2019;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RefrectTest {

	public static void main(String[] args) throws Exception {
		String resultType = "com.ctcf._2019.Cat";
		List<Map<String, Object>> result = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("name", "cat1");
		map.put("age", 1);
		result.add(map);
		
		Cat cat = (Cat) format(result, resultType);
		System.out.println(cat);
		
		Map<String, Object> map2 = new HashMap<>();
		map2.put("name", "cat2");
		map2.put("age", 2);
		result.add(map2);
		List<Cat> list = (List<Cat>) format(result, resultType);
		System.out.println(list);
	}
	
	public static Object format(List<Map<String, Object>> result, String resultType) throws Exception{
		Class clz = Class.forName(resultType);
		Method[] methods = clz.getDeclaredMethods();
		if(result.size()>1){
			List<Object> list = new ArrayList<>();
			for(Map<String, Object> resultMap: result){
				Object o = clz.newInstance();
				for(Method method: methods){
					String methodName = formatMethodName(method.getName());
					if(resultMap.containsKey(methodName)){
						method.invoke(o, resultMap.get(methodName));
					}
				}
				list.add(o);
			}
			return list;
		}else{
			Object o = clz.newInstance();
			Map<String, Object> resultMap = result.get(0);
			for(Method method: methods){
				String methodName = formatMethodName(method.getName());
				if(resultMap.containsKey(methodName)){
					method.invoke(o, resultMap.get(methodName));
				}
			}
			return o;
		}
	}
	
	public static String formatMethodName(String name){
		if(name.startsWith("set") && name.length()>4){
			return name.substring(3, 4).toLowerCase() + name.substring(4);
		}else{
			return name;
		}
	}
	
}


class Cat{
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}
}

执行结果:

Cat [name=cat1, age=1]
[Cat [name=cat1, age=1], Cat [name=cat2, age=2]]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值