Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type

今天做了一个Map转java对象的例子,用了一种比较简单的方法,就是通过net.sf.cglib.beans.BeanMap类中的方法进行转换。结果在一切准备就绪,执行的时候报错了,如下:

Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type
	at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:184)
	at net.sf.cglib.core.KeyFactory.(KeyFactory.java:66)
	at net.sf.cglib.beans.BeanMap$Generator.(BeanMap.java:64)
	at net.sf.cglib.beans.BeanMap.create(BeanMap.java:56)
	at com.example2.pojo.MapToPojo.mapToBean(MapToPojo.java:27)
	at com.example2.pojo.MapToPojo.main(MapToPojo.java:18)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
	at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
	at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
	... 6 more

先贴上本例的主要代码吧:

package com.example2.pojo;

import java.util.HashMap;
import java.util.Map;

import net.sf.cglib.beans.BeanMap;

public class MapToPojo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map map = new HashMap();
		map.put("name", "张三");
		map.put("age", 30);
		try {
			Employee employee = (Employee) mapToBean(map, Employee.class);
			System.out.print(employee.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    public static Object mapToBean(Map map, Class beanClass) throws Exception {
    	Object object = beanClass.newInstance();
        BeanMap beanMap = BeanMap.create(object);
        beanMap.putAll(map);
        return object;
    }

}

Employee类:

package com.example2.pojo;

public class Employee {

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

从错误信息上看,是缺少了org.objectweb.asm.Type类,那么找一个就OK了,从网上下载了com.springsource.org.objectweb.asm-3.2.0.jar包,引入后,再次执行,成功。 Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type_第1张图片

补充:其实项目中已引入的spring-core-4.1.7.RELEASE.jar包中也已经集成了cglib模块,如图:Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type_第2张图片

引用这个包里的BeanMap类也可以,

import org.springframework.cglib.beans.BeanMap;

执行后,达到同样效果。

你可能感兴趣的:(java)