简体   繁体   English

类被多次实例化; 如何分辨正在呼叫哪一个?

[英]Class instantiated multiple times; how to tell which one is being called?

I am working on the following code, where the same class is instantiated twice with two different names: 我正在处理以下代码,其中使用两个不同的名称实例化相同的类两次:

private final CdsResEventRepository hcrsResEventRepo;
private final CdsResEventRepository pcrsResEventRepo;
...
if (queueRec.getDbId() == DbId.HCRS) {
  delCnt = hcrsResEventRepo.delete(seqId);
} else if (queueRec.getDbId() == DbId.PCRS) {
  delCnt = pcrsResEventRepo.delete(seqId);
}

Depending on the condition, the same method may be called with one class name or the other. 根据条件,可以使用一个类名或另一个类名来调用相同的方法。

From inside CdsResEventRepository.delete, how can I tell whether it was called as hcrsResEventRepo.delete or pcrsResEventRepo.delete? 从CdsResEventRepository.delete内部,如何知道它是被称为hcrsResEventRepo.delete还是pcrsResEventRepo.delete?

My first thought was to use getStackTrace() to get the called Class. 我的第一个想法是使用getStackTrace()获取被调用的Class。 However, this returns only "CdsResEventRepository", and does not tell whether it was the hcrsResEventRepo instantiation or the pcrsResEventRepo instantiation. 但是,这仅返回“ CdsResEventRepository”,并且不告诉它是hcrsResEventRepo实例还是pcrsResEventRepo实例。

From within the method being called, what is the best way to tell which instantiation was used to call it? 从被调用的方法中,最好的方法是告诉使用哪个实例来调用它?

What about a booleand flag? 那布兰德旗呢? boolean wasCalled , if you can modify your class. boolean wasCalled ,如果可以修改您的类。 If you can't, a boolean variable between lines. 如果不能,则在行之间使用布尔变量。 A quick solution, but works. 快速解决方案,但是可行。

boolean hcrsResEventRepoDeleted = false;
if (queueRec.getDbId() == DbId.HCRS) {
  delCnt = hcrsResEventRepo.delete(seqId);
  hcrsResEventRepoDeleted = true;
} else if (queueRec.getDbId() == DbId.PCRS) {
  delCnt = pcrsResEventRepo.delete(seqId);
}

Then do something with the boolean. 然后用布尔值做一些事情。 If you have access to you class: 如果您有权访问您的课程:

delCntH = hcrsResEventRepo.delete(seqId, DbId.HCRS, queueRec.getDbId());
delCntP = hcrsResEventRepo.delete(seqId, DbId.PCRS, queueRec.getDbId());

and call queueRec.delete(seqId) inside that new delete method with the if logic and the extra info; 并使用if逻辑和额外信息在该新的delete方法中queueRec.delete(seqId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM