Java反射实战 书籍推荐,Java反射实战

背景

使用spring-ldap操作LDAP,完成LdapTemplate设置后,进行多条件查询,因为需求是能够多条件查询,所以在使用ldapTemplate.search系列方法时,着重考虑了下面的重载实现,第二个参数直接写过滤条件,只要按过滤语法书写即可,胜任各种复杂查询。

List users = ldapTemplate.search("ou=People", "(&(objectClass=person)(smart-type=E1))", new AttributesMapper() {

@Override

public LdapUser mapFromAttributes(Attributes attributes) throws NamingException {

return null;

}

});

但是这个查询的,不能使用spring-ldap的ODM,不能把LDAP返回的查询结果,直接转成POJO;也就是需要自己把Attributes attributes转成我需要的LdapUser实体对象。

LdapUser.java如下

import lombok.Getter;

import lombok.Setter;

import org.springframework.ldap.odm.annotations.Attribute;

import org.springframework.ldap.odm.annotations.Entry;

import org.springframework.ldap.odm.annotations.Id;

import javax.naming.Name;

@Setter

@Getter

@Entry(objectClasses = { "inetOrgPerson" ,"top","person" },base="ou=People") // ou=Internal, (只指定People,可按uid查询单个人员)

public class LdapUser extends BaseDTO {

@Id

protected Name dn;

@Attribute(name = "uid")

protected String uid;

@Attribute(name = "smart-type")

protected String userType;

@Attribute(name = "mail")

protected String mail;

@Attribute(name = "mobile")

protected String mobile;

@Attribute(name = "departmentNumber")

protected String deptId;

@Attribute(name = "departmentName")

protected String deptName;

// ...

}

}

这个POJO使用了spring-ldap 的ODM注解,类和属性分别使用了@Entry

和@Attribute(name = "uid"),其中@Attribute 中的name则标识LDAP查询返回的Attributes 中的一个属性的名称。

下面要做的反射任务

就是读取到POJO 这个LdapUser实体类中所有有带Attribute的属性,拿取到name后,从查询返回结果的Attributes 中遍历拿到对应name的 值,利用反射,给bean设置属性值。实现如下:

List users = ldapTemplate.search("ou=People", "(&(objectClass=person)(smart-type=E1))", new AttributesMapper() {

@Override

public LdapUser mapFromAttributes(Attributes attributes) throws NamingException {

LdapUser bean = null;

if (LdapUser.class.isAnnotationPresent(Entry.class)) {//是否加@Entry

try {

bean = LdapUser.class.newInstance();

} catch (Exception e) {

throw new RuntimeException("反射创建PIJO[]实例对象失败",e);

}

Field[] fields = LdapUser.class.getDeclaredFields();//拿到bean对应的属性

for (Field field : fields) {//遍历POJO 所有属性

boolean fieldHasAnno = field.isAnnotationPresent(Attribute.class);//类属性上是否加@Attribute(name = "smart-type")

if (fieldHasAnno) {

Attribute fieldAnno = field.getAnnotation(Attribute.class);

String name = fieldAnno.name();//注解的name值,如smart-type

for (NamingEnumeration attrEnumeration = attributes.getAll(); attrEnumeration.hasMore(); ) {

javax.naming.directory.Attribute attr = (javax.naming.directory.Attribute) attrEnumeration.next();

String ldapAttr = attr.getID();

if (ldapAttr.equals(name)) {

String ldapValue = attr.get().toString();

setProperty(bean, field.getName(), ldapValue);//反射:给bean设置属性值

} else {

continue;

}

}

}

}

} else {

throw new RuntimeException("PIJO[]需使用@Entry注解");

}

return bean;

}

});

/**

* 反射:给bean设置属性值

*

* @param bean

* @param name

* @param value

*/

private void setProperty(Object bean, String name, Object value) {

String setterName = "set" + StringUtils.capitalize(name);

Method setter;

try {

setter = bean.getClass().getMethod(setterName, value.getClass());

setter.invoke(bean, value);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

因为考虑到通用性,就把这一部分反射的工作抽象出来,用泛型替换具体类型,

实现了一个通用的转化ConvertAttributesMapper

import org.apache.commons.lang3.StringUtils;

import org.springframework.ldap.core.AttributesMapper;

import org.springframework.ldap.odm.annotations.Attribute;

import org.springframework.ldap.odm.annotations.Entry;

import javax.naming.NamingEnumeration;

import javax.naming.NamingException;

import javax.naming.directory.Attributes;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

/**

* 实现Attributes 转成POJO

*/

public class ConvertAttributesMapper implements AttributesMapper {

Class clazz;

public ConvertAttributesMapper(Class clazz) {

this.clazz = clazz;

}

@Override

public T mapFromAttributes(Attributes attributes) throws NamingException {

T bean = null;

if (clazz.isAnnotationPresent(Entry.class)) {//是否加@Entry

try {

bean = clazz.newInstance();

} catch (Exception e) {

throw new RuntimeException("反射创建PIJO[]实例对象失败",e);

}

Field[] fields = clazz.getDeclaredFields();//拿到bean对应的属性

for (Field field : fields) {//遍历POJO 所有属性

boolean fieldHasAnno = field.isAnnotationPresent(Attribute.class);//类属性上是否加@Attribute(name = "smart-type")

if (fieldHasAnno) {

Attribute fieldAnno = field.getAnnotation(Attribute.class);

String name = fieldAnno.name();//注解的name值,如smart-type

for (NamingEnumeration attrEnumeration = attributes.getAll(); attrEnumeration.hasMore(); ) {

javax.naming.directory.Attribute attr = (javax.naming.directory.Attribute) attrEnumeration.next();

String ldapAttr = attr.getID();

if (ldapAttr.equals(name)) {

String ldapValue = attr.get().toString();

setProperty(bean, field.getName(), ldapValue);//反射:给bean设置属性值

} else {

continue;

}

}

}

}

} else {

throw new RuntimeException("PIJO[]需使用@Entry注解");

}

return bean;

}

/**

* 反射:给bean设置属性值

*

* @param bean

* @param name

* @param value

*/

private void setProperty(Object bean, String name, Object value) {

String setterName = "set" + StringUtils.capitalize(name);

Method setter;

try {

setter = bean.getClass().getMethod(setterName, value.getClass());

setter.invoke(bean, value);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

}

//使用样例

AttributesMapper attributesMapper = new ConvertAttributesMapper(LdapUser.class);

List users = ldapTemplate.search("ou=People", "(&(objectClass=person)(smart-type=E1))", attributesMapper);

ps:BaseDTO是一个空的抽象类。