Java 中的委托类似于 .NET 中的委托
我需要一些关于 Java 方法的建议,因为委托与 .NET 有点不同。我想创建一些具有相同名称和相同方法名称的接口,但唯一不同的是参数数量。类似 .NET 中的 Actions 的内容
一些代码示例。
现在起作用的是像这样实现的抽象类。
public abstract class AbstractValidators {
public <T1> boolean isValid(T1 t1) {
return false;
}
public <T1,T2> boolean isValid(T1 t1, T2 t2) {
return false;
}
//And so one
}
然后在某个课堂上我们可以做这样的事情。
public class SomeClass {
AbstractValidators validateStrVsInter = new AbstractValidators() {
public <String,Integer> boolean isValid(String t1, Integer t2) { //Don't be fool by colors the String and Integer are only names of generic parameters
return true;
}
};
public void doStaff() {
this.validateStrVsInter.<String,Integer>isValid("String", 100); // return true;
}
}
这项工作可行,但不是很好的解决方案,恕我直言,我需要的是可以分配给一个的各种接口之类的东西。
public interface IValidator<T1> {
public boolean isValid(T1 t);
}
public interface IValidator<T1,T2> {
public boolean isValid(T1 t, T2 t2);
}
一些想法?
编辑:
目标是什么?
非常简单,可以
isValid(String t1, Integer t2) { }
将定义更改为
isValid(String t1, Integer t2, Double t3) { }
和调用中。
validator.isValid("1",2);
情况下
validator.isValid("1",2, 3.0);
在不更改类导入等的
I need some advise regarding approach in Java, as the delegates are bit different than .NET one. I wold like to create some interfaces that has the same name and same method name but only thing that differ them is number of parameters. Something like Actions in .NET
Some code samples.
What works for now is the abstract class implemented like this.
public abstract class AbstractValidators {
public <T1> boolean isValid(T1 t1) {
return false;
}
public <T1,T2> boolean isValid(T1 t1, T2 t2) {
return false;
}
//And so one
}
Then in some class we can do something like this.
public class SomeClass {
AbstractValidators validateStrVsInter = new AbstractValidators() {
public <String,Integer> boolean isValid(String t1, Integer t2) { //Don't be fool by colors the String and Integer are only names of generic parameters
return true;
}
};
public void doStaff() {
this.validateStrVsInter.<String,Integer>isValid("String", 100); // return true;
}
}
That work but is not nice solution IMHO what i need is something like various interafaces that could be assigned to one..
public interface IValidator<T1> {
public boolean isValid(T1 t);
}
public interface IValidator<T1,T2> {
public boolean isValid(T1 t, T2 t2);
}
Some ideas ?
EDIT:
What the goal is ?
Very simple to have possibility to change definition
isValid(String t1, Integer t2) { }
into
isValid(String t1, Integer t2, Double t3) { }
and in invocation
validator.isValid("1",2);
to
validator.isValid("1",2, 3.0);
Without changing class import etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您知道您可以创建一个实现多个其他接口的接口,本质上是连接它们吗?
You are aware that you can create an interface implementing multiple other interfaces essentially joining them?
在接口的实现中使用包名。
Use the packagename in the implementation of the interface.