[英]How to pass different object type for same method instead of writing two methods with same functionality and return type in java
here is my methods i want to make it dynamic which should accept class type as parameter and then i can use that in my predicate i have tried using instanceof but didnt work这是我想让它动态化的方法,它应该接受 class 类型作为参数,然后我可以在我的谓词中使用它我已经尝试使用 instanceof 但没有用
public static String setStatus(List<SmeObject> s) {
String finalStatus = "";
Predicate<SmeObject> ifAllCompleted = x.getStatus().equals("Completed");
Predicate<SmeObject> ifAllNotStarted = x.getStatus().equals("Not Started");
if (s.stream().allMatch(ifAllCompleted)) {
finalStatus = "Complete";
} else if (s.stream().allMatch(ifAllNotStarted)) {
finalStatus = "Not Started";
} else {
finalStatus = "In-progress";
}
return finalStatus;
}
public static String setStatus(List<ControllerObject> s) {
String finalStatus = "";
Predicate<ControllerObject> ifAllCompleted = x.getStatus().equals("Completed");
Predicate<ControllerObject> ifAllNotStarted = x.getStatus().equals("Not Started");
if (s.stream().allMatch(ifAllCompleted)) {
finalStatus = "Complete";
} else if (s.stream().allMatch(ifAllNotStarted)) {
finalStatus = "Not Started";
} else {
finalStatus = "In-progress";
}
return finalStatus;
}
If ControllerObject
and SmeObject
share a common parent that exposes the getStatus()
method, then you may want to make your method take a list with a List<? extends CommonObjectSuperType>
如果
ControllerObject
和SmeObject
共享一个公开getStatus()
方法的公共父级,那么您可能希望让您的方法获取一个带有List<? extends CommonObjectSuperType>
List<? extends CommonObjectSuperType>
: List<? extends CommonObjectSuperType>
:
public static String setStatus(List<? extends CommonObjectSuperType> s) {
String finalStatus = "";
Predicate<CommonObjectSuperType> ifAllCompleted = x.getStatus().equals("Completed");
Predicate<CommonObjectSuperType> ifAllNotStarted = x.getStatus().equals("Not Started");
...
}
If, however, ControllerObject
and SmeObject
do not have a common parent that exposes getStatus()
and you can't change them, then you're left with the option of making the caller send in a predicate by making the method generic:但是,如果
ControllerObject
和SmeObject
没有公开getStatus()
的公共父级并且您无法更改它们,那么您可以选择通过使方法通用来让调用者发送谓词:
public static <T> String setStatus(List<T> s, Predicate<T> allCompletedTest,
Predicate<T> allNotStartedTest) {
//use incoming predicates instead of creating them in the method
...
}
Then the caller will create the predicates in the context of the actual type.然后调用者将在实际类型的上下文中创建谓词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.