开发者

Delegates in Java like in .NET

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 wha开发者_StackOverflow中文版t 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.


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.

public class interfaces implements package.a.IValidator, package.b.IValidator
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜