问题1:
想写个requestInfo的toString方法,把所有的成员变量都打印出来,子类就不用每次都写个toString方法了,但是父类怎么获取子类成员变量的值?
public class RequestInfo
{
public String toString()
{
StringBuilder sb = new StringBuilder();
Field[] fields = this.getClass().getDeclaredFields();
for(Field field : fields)
{
sb.append(field.getName(), " = ", (这里怎么获取属性值?), ";");
}
return "";
}
}
问题2
下面那个类P怎么实例化,也没懂错误的原因,用P.getClass()还是不行
public abstract class AbstractService<Q extends RequestInfo, P extends ResponseInfo>
{
public static final Logger LOGGER = LoggerFactory.getLogger(AbstractService.class);
private String logTag;
private P respBean;
public P execute(Q reqBean)
{
init();
LOGGER.info(StringUtil.appendStr("Request : {}, req = {}", logTag, reqBean.toString()));
try
{
if (checkInput(reqBean))
{
handle(reqBean, respBean);
}
else
{
throw new Exception(StringUtil.appendStr(logTag, " check input param invalid"));
}
}
catch (Exception e)
{
LOGGER.error(StringUtil.appendStr(logTag, " Exception: "), e);
}
return respBean;
}
protected void init()
{
logTag = getClass().getSimpleName();
respBean =P.class.newInsance();//这里报错,cannot select from a type variable
}
protected boolean checkInput(Q reqBean)
{
return true;
}
protected abstract void handle(Q reqBean, P respBean)
throws Exception;
}
饮歌长啸
BIG阳
相关分类