问题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;
}
Generics have been erased after compilation. The jvm cannot see the generic information at all. This is due to historical reasons, so the p.getClass you mentioned cannot exist
The first question is a good idea, but as far as I know it cannot be implemented. The object cannot know the status of the subclass. Java's polymorphic mechanism can only query methods from the parent class or parent interface.
I guess the first question you think you can get the member variables of a subclass is that once the toString method of the subclass is executed after inheritance, your own this will also be called, which is wrong. At run time, the jvm will obtain this method from the object space of the parent class and execute it. So, no matter what, they are just member variables of the parent class
I made a mistake in the above italicized part. After running the IDE to test it, I found that I was wrong about what I understood before. I hope it didn’t cause trouble to the questioner.
The code posted below can loop to obtain all variables from the subclass to the parent class. Hope it helps
Reflection tool class
Question 1
Question 2
The first question can be solved using commons-beanutils.