开发者

Preprocessor variables in Java

I am developing with GWT and share a codebase with an Android developer. Some functions we want to share t开发者_开发技巧ake speciffic arguments like "Drawable" under Android and "Image" under GWT.

Is it possible to use a preprocessor variable as in C++:

#ifdef ANDROID
public void DrawImg(Drawable img);
#elif GWT
public void DrawImg(Image img);
#endif

The solution we are testing is a Generic like this:

interface DrawImgInterf<T extends Object> {
    public void DrawImg(T img);
}

However using a preproccesor variable seems better. Is there such a thing in Java?


No, there's nothing like that in normal Java. You could run a preprocessor of course, but that will make it painful to develop the code. (Anything like an IDE which expects the code to be "normal" Java is going to get confused.)

Have you considered using an interface instead, which abstracts out the common operations, and binds to the appropriate real type at execution time? That won't always work (as adding a proxy breaks situations where object identity is important) but in some cases it can be helpful.


No, there are no preprocessor variables in Java.


for such cases it is the best way to use a preprocessor I used it for my J2ME developments http://code.google.com/p/java-comment-preprocessor/wiki/ExampleOfUsageForJ2ME


Java+ is a preprocessor which can perform substitution using resource bundles:

public static void 
main(String[] args)
{
  System.out.println({{
The answer,
my dearest, 
is {{computeAnswer()}}.
  }});
}
static String computeAnswer()
{
  return {{my computed answer}};
}

References

  • java+.tgz
  • java+.dmg


Employing Visitor Pattern here, is making sense to me. For example,

interface ImageVisitor {
    void visit(GWTImage image);
    void visit(AndroidImage image);
}

interface IImage {
    void accept(ImageVisitor visitor);
}

class GWTImage implements IImage {
    ..
    public void accept(ImageVisitor visitor) {
        visitor.visit(this);
    }
    ..
}

class AndroidImage implements IImage {
    ..
    public void accept(ImageVisitor visitor) {
        visitor.visit(this);
    }
    ..
}

class GWTImageVisitor implements ImageVisitor {    
    public void visit(GWTImage image) {      
        Image img = image.getImage();
        ..
    }
}

class AndroidImageVisitor implements ImageVisitor {    
    public void visit(AndroidImage image) {      
        Drawable drawable = image.getDrawable();
        ..
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜