samedi 2 avril 2022

Java: make static methods of one class mirror instance methods of another class

I have a POJO like this:

public class Foo {
    private String bar1;
    private String bar2;
    //...

    public String getBar1() { return bar1; } 
    public void setBar1(String bar1) { this.bar1 = bar1; }
    public String getBar2() { return bar2; } 
    public void setBar2(String bar2) { this.bar2 = bar2; }
    //...
}

As an alternative to Java reflection (which is quite slow in general), I would like to define a class with static methods like this:

public class FooStatic {

    public static String getBar1(Foo foo) { return foo.getBar1(); } 
    public static void setBar1(Foo foo, String bar1) { foo.setBar1(bar1); }
    public static String getBar2(Foo foo) { return foo.getBar2(); } 
    public static void setBar2(Foo foo, String bar2) { foo.setBar2(bar2); }
    //...
}

which enforces the creation/deprecation of a static method every time the Foo class is updated. For example, if the field bar2 is deleted in FooStatic, then the static methods getBar2() and setBar2() in FooStatic should be identified by the compiler to be removed. If a new variable bar3 is added to Foo with getters and setters, the compiler should enforce the creation of new static methods getBar3() and setBar3() in FooStatic. Moreover, I have multiple POJOs, and would like a solution which scales. Is this possible?





Aucun commentaire:

Enregistrer un commentaire