开发者

Eclipse supress compiler error - Is there a possible work around?

开发者 https://www.devze.com 2023-03-14 19:58 出处:网络
Here\'s the scenario: I have a program that contains an annotation that I built out in my eclipse project, it\'s called \'flag\'.

Here's the scenario:

I have a program that contains an annotation that I built out in my eclipse project, it's called 'flag'. The 'flag' annotation has an 'id' element I have a method in my class called 'connect' that establishes a socket connection. I annotate the connect method by placing the 'flag' annotation before it and give it an 'id'

public class Foo {
   @flag(id = 'slowConnection')
   public boolean connect() {
      // connect logic here...
   }
}

Now, what I ultimately want is something like the following

public class Foo {
   @flag(id = 'slowConnection')
   public boolean connect() {
      // connect logic here...
   }

   @flag(id = 'mediumConnection')
   public boolean connect() {
      // medium connection logic here
   }

   @flag(id = 'fastConnection')
   public boolean connect() {
      // fast connection logic here
   }
}

Allow me to elaborate here. My objective is to be able to only include the correct 'connect' method at compile time based on an input parameter to the class. Method overloading is a similar way 开发者_运维技巧to do this, albeit I don't want to change the method signature. I'm also aware that inheritance would be a way to do this. Eclipse (rightly so) complains when I have the above code, saying that there's a duplicate method. Is there anyway that I could proceed with the above in Eclipse before I compile the program as I will perform some logic to strip out all but one of the 'connect' methods before the program is compiled? Is there a way to automatically disable auto-compilation in eclipse? Any tips or pointers would be helpful.


You move the connection logic to a separate interface and then use the factory pattern to generate the appropriate connection:

public interface IFoo {
   void connect();
}

final class SlowFoo implements IFoo {
  //Implementation for slow connections
} 

final class MediumFoo implements IFoo {
  //Implementation for medium connections
} 

final class FastFoo implements IFoo {
  //Implementation for fast connections
} 

If the classes share common code, you should consider introducing a base class like FooBase.

The factory could then look like this:

public final class FooFactory {
   public IFoo create() {
      if (Connection.speed < 100) //Fictive value
          return new SlowFoo();
      if (Connection.speed < 1000) //Fictive value
          return new MediumFoo();

      return new FastFoo();
   }
}

Messing around with the source code before compilation is not a good idea IMHO.

0

精彩评论

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