我也讨厌写 getter 和 setter。我更喜欢使用 POJO,甚至是声明为嵌套类的 POJO。
还有另一种方法可以做到这一点,即使使用旧的服务器和技术并且不引入 Springs(我们使用 JBoss 4.2 和 JBoss 不完整的 EJB 3.0)。扩展 org.apache.commons.beanutils.BeanMap,您可以将 POJO 包装在一个 bean map 中,当您获取或放置时,您可以使用反射操作字段。如果 getter 或 setter 不存在,我们只需使用字段操作来获取它。显然它不是真正的豆子,所以这完全没问题。
package com.aaa.ejb.common;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections.set.UnmodifiableSet;
import org.apache.log4j.Logger;
/**
* I want the bean map to be able to handle a POJO.
* @author gbishop
*/
public final class NoGetterBeanMap extends BeanMap {
private static final Logger LOG = Logger.getLogger(NoGetterBeanMap.class);
/**
* Gets a bean map that can handle writing to a pojo with no getters or setters.
* @param bean
*/
public NoGetterBeanMap(Object bean) {
super(bean);
}
/* (non-Javadoc)
* @see org.apache.commons.beanutils.BeanMap#get(java.lang.Object)
*/
public Object get(Object name) {
Object bean = getBean();
if ( bean != null ) {
Method method = getReadMethod( name );
if ( method != null ) {
try {
return method.invoke( bean, NULL_ARGUMENTS );
}
catch ( IllegalAccessException e ) {
logWarn( e );
}
catch ( IllegalArgumentException e ) {
logWarn( e );
}
catch ( InvocationTargetException e ) {
logWarn( e );
}
catch ( NullPointerException e ) {
logWarn( e );
}
} else {
if(name instanceof String) {
Class<?> c = bean.getClass();
try {
Field datafield = c.getDeclaredField( (String)name );
datafield.setAccessible(true);
return datafield.get(bean);
} catch (SecurityException e) {
throw new IllegalArgumentException( e.getMessage() );
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException( e.getMessage() );
} catch (IllegalAccessException e) {
throw new IllegalArgumentException( e.getMessage() );
}
}
}
}
return null;
}
/* (non-Javadoc)
* @see org.apache.commons.beanutils.BeanMap#put(java.lang.Object, java.lang.Object)
*/
public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException {
Object bean = getBean();
if ( bean != null ) {
Object oldValue = get( name );
Method method = getWriteMethod( name );
Object newValue = null;
if ( method == null ) {
if(name instanceof String) {//I'm going to try setting the property directly on the bean.
Class<?> c = bean.getClass();
try {
Field datafield = c.getDeclaredField( (String)name );
datafield.setAccessible(true);
datafield.set(bean, value);
newValue = datafield.get(bean);
} catch (SecurityException e) {
throw new IllegalArgumentException( e.getMessage() );
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException( e.getMessage() );
} catch (IllegalAccessException e) {
throw new IllegalArgumentException( e.getMessage() );
}
} else {
throw new IllegalArgumentException( "The bean of type: "+
bean.getClass().getName() + " has no property called: " + name );
}
} else {
try {
Object[] arguments = createWriteMethodArguments( method, value );
method.invoke( bean, arguments );
newValue = get( name );
} catch ( InvocationTargetException e ) {
logInfo( e );
throw new IllegalArgumentException( e.getMessage() );
} catch ( IllegalAccessException e ) {
logInfo( e );
throw new IllegalArgumentException( e.getMessage() );
}
firePropertyChange( name, oldValue, newValue );
}
return oldValue;
}
return null;
}
/* (non-Javadoc)
* @see org.apache.commons.beanutils.BeanMap#keySet()
*/
public Set keySet() {
Class<?> c = getBean().getClass();
Field[] fields = c.getDeclaredFields();
Set<String> keySet = new HashSet<String>(super.keySet());
for(Field f: fields){
if( Modifier.isPublic(f.getModifiers()) && !keySet.contains(f.getName())){
keySet.add(f.getName());
}
}
keySet.remove("class");
return UnmodifiableSet.decorate(keySet);
}
}
棘手的部分是分解 POJO 以返回,但反射可以帮助您:
/**
* Returns a new instance of the specified object. If the object is a bean,
* (serializable, with a default zero argument constructor), the default
* constructor is called. If the object is a Cloneable, it is cloned, if the
* object is a POJO or a nested POJO, it is cloned using the default
* zero argument constructor through reflection. Such objects should only be
* used as transfer objects since their constructors and initialization code
* (if any) have not have been called.
* @param obj
* @return A new copy of the object, it's fields are blank.
*/
public static Object constructBeanOrPOJO(final Object obj) {
Constructor<?> ctor = null;
Object retval = null;
//Try to invoke where it's Serializable and has a public zero argument constructor.
if(obj instanceof Serializable){
try {
ctor = obj.getClass().getConstructor((Class<?>)null);
if(ctor.isAccessible()){
retval = ctor.newInstance();
//LOG.info("Serializable class called with a public constructor.");
return retval;
}
} catch (Exception ignoredTryConeable) {
}
}
//Maybe it's Clonable.
if(obj instanceof Cloneable){
try {
Method clone = obj.getClass().getMethod("clone");
clone.setAccessible(true);
retval = clone.invoke(obj);
//LOG.info("Cloneable class called.");
return retval;
} catch (Exception ignoredTryUnNestedClass) {
}
}
try {
//Maybe it's not a nested class.
ctor = obj.getClass().getDeclaredConstructor((Class<?>)null);
ctor.setAccessible(true);
retval = ctor.newInstance();
//LOG.info("Class called with no public constructor.");
return retval;
} catch (Exception ignoredTryNestedClass) {
}
try {
Constructor[] cs = obj.getClass().getDeclaredConstructors();
for(Constructor<?> c: cs){
if(c.getTypeParameters().length==0){
ctor = c;
ctor.setAccessible(true);
retval = ctor.newInstance();
return retval;
}
}
//Try a nested class class.
Field parent = obj.getClass().getDeclaredField("this$0");
parent.setAccessible(true);
Object outer = (Object) parent.get(obj);
//ctor = (Constructor<? extends Object>) obj.getClass().getConstructors()[0];//NO, getDECLAREDConstructors!!!
ctor = (Constructor<? extends Object>) obj.getClass().getDeclaredConstructor(parent.get(obj).getClass());
ctor.setAccessible(true);
retval = ctor.newInstance(outer);
//LOG.info("Nested class called with no public constructor.");
return retval;
} catch (Exception failure) {
throw new IllegalArgumentException(failure);
}
}
从 bean、可克隆或 POJO 获取通用 bean 的示例代码:
public List<Object> getGenericEJBData(String tableName, Object desiredFields, Object beanCriteria){
NoGetterBeanMap desiredFieldMap = new NoGetterBeanMap(desiredFields);
NoGetterBeanMap criteriaMap = new NoGetterBeanMap(beanCriteria);
List<Object> data = new ArrayList<Object>();
List<Map<String, Object>> mapData = getGenericEJBData(tableName, desiredFieldMap, criteriaMap);
for (Map<String,Object> row: mapData) {
Object bean = NoGetterBeanMap.constructBeanOrPOJO(desiredFields);//Cool eh?
new NoGetterBeanMap(bean).putAll(row);//Put the data back in too!
data.add(bean);
}
return data;
}
EJB 的示例用法:
IGenericBean genericRemote = BeanLocator.lookup(IGenericBean.class);
//This is the minimum required typing.
class DesiredDataPOJO {
public String makename="";//Name matches column and return type.
}
class CriteriaPOJO {
//Names match column and contains criteria values.
public String modelname=model,yearid=year;
}
List<DesiredDataPOJO> data =
genericRemote.getGenericEJBData(ACES_VEHICLE_TABLE, new DesiredDataPOJO(), new CriteriaPOJO() );
for (DesiredDataPOJO o: data) {
makes.add(o.makename);
}
EJB 有一个这样的接口:
package com.aaa.ejb.common.interfaces;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.ejb.Remote;
/**
* @see
* http://trycatchfinally.blogspot.com/2006/03/remote-or-local-interface.html
*
* Note that the local and remote interfaces extend a common business interface.
* Also note that the local and remote interfaces are nested within the business
* interface. I like this model because it reduces the clutter, keeps related
* interfaces together, and eases understanding.
*
* When using dependency injection, you can specify explicitly whether you want
* the remote or local interface. For example:
* @EJB(beanInterface=services.DistrictService.IRemote.class)
* public final void setDistrictService(DistrictService districtService) {
* this.districtService = districtService;
* }
*/
public interface IGenericBean {
@Remote
public interface IRemote extends IGenericBean {
}
@Local
public interface ILocal extends IGenericBean {
}
/**
* Gets a list of beans containing data.
* Requires a table name and pair of beans containing the fields
* to return and the criteria to use.
*
* You can even use anonymous inner classes for the criteria.
* EX: new Object() { public String modelname=model,yearid=year; }
*
* @param tableName
* @param fields
* @param criteria
* @return
*/
public <DesiredFields> List<DesiredFields> getGenericEJBData(String tableName, DesiredFields desiredFields, Object beanCriteria);
}
你可以想象 ejb 实现是什么样子的,现在我们正在构建准备好的语句并调用它们,但我们可以使用条件,或者像 hibernate 这样更酷的东西,或者如果我们想要的任何东西。
这是一个粗略的例子(有些人不会喜欢这部分)。在示例中,我们有一个包含第三范式数据的表。为此,bean 字段必须与表列名称匹配。toLowerCase() 调用以防万一这是一个正在使用的 REAL bean,这将搞砸名称匹配(MyField 与 getMyfield)。这部分可能会抛光得更好一些。特别是 order by 和 distinct 应该是 flags 或其他东西。可能还有其他边缘条件也可能发生。当然,我只需要编写一次,就性能而言,没有什么能阻止您获得更精确的性能数据接收器。
@Stateless
public class GenericBean implements ILocal, IRemote {
...
/* (non-Javadoc)
* @see com.aaa.ejb.acesvehicle.beans.interfaces.IAcesVehicleBean#getGenericEJBData(java.lang.String, java.util.Map, java.util.Map)
*/
@Override
public List<Map<String, Object>> getGenericEJBData(String tableName,Map<String, Object> desiredFields, Map<String, Object> criteria){
try {
List<Map<String,Object>> dataFieldKeyValuePairs = new ArrayList<Map<String,Object>>();
StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
int selectDistinctLength = sql.length();
for(Object key : desiredFields.keySet()){
if(desiredFields.get(key)!=null) {
sql.append(key).append(", ");
}
}
sql.setLength(sql.length()-2);//Remove last COMMA.
int fieldsLength = sql.length();
sql.append(" FROM ").append(tableName).append(" WHERE ");
String sep = "";//I like this, I like it a lot.
for(Object key : criteria.keySet()){
sql.append(sep);
sql.append(key).append(" = COALESCE(?,").append(key).append(") ");
sep = "AND ";
}
sql.append(" ORDER BY ").append(sql.substring(selectDistinctLength, fieldsLength));
PreparedStatement ps = connection.prepareStatement(sql.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int criteriaCounter=1;
for(Object key : criteria.keySet()){
ps.setObject(criteriaCounter++, criteria.get(key));
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Map<String,Object> data = new HashMap<String,Object>();
int columnIndex = rs.getMetaData().getColumnCount();
for(int x=0;x<columnIndex;x++){
String columnName = rs.getMetaData().getColumnName(x+1);
if(desiredFields.keySet().contains(columnName.toLowerCase())){
//Handle bean getters and setters with different case than metadata case.
data.put(columnName.toLowerCase(), rs.getObject(x+1));
} else {
data.put(columnName, rs.getObject(x+1));
}
}
dataFieldKeyValuePairs.add(data);
}
rs.close();
ps.close();
return dataFieldKeyValuePairs;
} catch (SQLException sqle) {
LOG.debug("National database access failed.", sqle);
throw new EJBException(new DataSourceException("Database access failed. \n"
+ "getGenericEJBData()", sqle.getMessage()));
}
}