package com.bx.test;
import com.bx.pojo.Tbbhinfo;
import java.beans.Introspector;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @Author Lhj
* @Date 2020/9/22 9:16
*/
public class ClassGet {
//获取类属性名
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IntrospectionException, InvocationTargetException {
User user = new User();
user.setUsername("zhanghao");
user.setUserpassword("mima");
Map<String, String> map = ClassGet.fun(user);
System.out.println(map);
}
//第一种方法
public static void method(Tbbhinfo obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Class clazz = obj.getClass();
Field[] fields = obj.getClass().getDeclaredFields();//获得属性bai
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();//获得get方法du
//System.out.println("getMethod---------"+getMethod);
Object o = getMethod.invoke(obj);//执行get方法返zhi回一个daoObject
System.out.println(o.toString());
}
}
//第二种
public static Map<String, String> fun(Object th){
Map<String, String> map = new HashMap<String, String>();
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(th.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class") && !key.equals("pageNo") && !key.equals("pageSize")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(th);
String value1 = value + "";
System.out.println("key:"+key+"--------"+"value1:"+value1);
map.put(key, value1);
}
}
System.out.println("反射转换完成");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return map;
}
}
实体类
package com.bx.test;
public class User {
private String username;
private String userpassword;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpassword() {
return userpassword;
}
public void setUserpassword(String userpassword) {
this.userpassword = userpassword;
}
}
输出结果
key:username--------value1:zhanghao
key:userpassword--------value1:mima
反射转换完成