1 2 Previous Next 21 Replies Latest reply: Jun 4, 2009 9:19 AM by 791266 RSS

    Generate getter/setter methods with annotations?

    843793
      Hi,

      Is there a way to automatically generate getter/setter methods with annotations? Something like:
      public class Test {
        @auto-getter-setter
        private int value;
      
        @auto-getter-setter
        private SomeType someType;
      }
      Thus, in runtime, this class would have the following auto-generated, standard methods available:
      public int getValue() { return value;}
      public void setValue(int value) { this.value = value;}
      
      public SomeType getSomeType() { return someType;}
      public void setSomeType(SomeType someType) { this.someType = someType;}
      Thanks
        • 1. Re: Generate getter/setter methods with annotations?
          608410
          Not directly.

          You cannot modify existing source files with annotation processing.

          However, you can generate a superclass (note you cannot use hyphens in names!)
          public class Test extends TestGen {
            @autogettersetter
            private int value;
           
            @autogettersetter
            private SomeType someType;
          }
          
          @Generated( bla bla bla )
          class TestGen { bla bla bla}
          which is hard to make work in this case because the fields need to be in the generated class (so the accessor methods can see them), and if you put them in Test also (so the processor can see them and generate the accessors), then they hide those in TestGen. One option there is to specify the name and type in the annotation.

          An alternative is to generate a subclass thus
          public class Test  {
          
            private Test() {}
          
            public static Test getInstance() {
                  return new TestGen();
          
            @autogettersetter
            protected int value;
           
            @autogettersetter
            protected SomeType someType;
          }
          
          @Generated( bla bla bla )
          class TestGen extends Test {
              public int getValue() { return value;}
              public void setValue(int value) { this.value = value;}
           
              public SomeType getSomeType() { return someType;}
              public void setSomeType(SomeType someType) { this.someType = someType;}
          }
          Another option if these are ONLY being used via the beans facility is to generate a TestBeanInfo which provides the accessor methods.
          • 2. Re: Generate getter/setter methods with annotations?
            843793
            You could use reflections and check whether the field is final to determine with whther to generate a setter.
            • 3. Re: Generate getter/setter methods with annotations?
              843793
              Thanks for the response.

              > You cannot modify existing source files with annotation processing.

              What about providing the generated getter/setter methods only at runtime? I do not even have the need to see the generated gettters/setters at all, the logic is obvious. Additional classes/subclasses make the benefits moot.

              My whole point of generating getter/setter methods was to make the source code cleaner and, as a result, simpler and easier to maintain. Completely dumb, obvious getter/setter method logic occupies thousands lines of code in our company's projects, cluttering the real logic with noise. It also take some time to create AND maintain all those getter/setter methods (yes, IDE helps but still...)
              • 4. Re: Generate getter/setter methods with annotations?
                dcminter
                It would also be possible, I think, to use a custom classloader that generated appropriate additions to the class on the fly on the basis of the compiletime annotations in the original.

                The problem with all these approaches, however, is that because they don't produce the class additions until runtime, you're stuck working with reflection to get at the new methods - which is probably more hassle than just creating them from scratch in the source code in the first place.

                I'd love to see some new compile-time feature added that meant that some suitable annotation resulted in the compiler generating an appropriate getter/setter pair for the field.
                • 5. Re: Generate getter/setter methods with annotations?
                  dcminter
                  Actually, having just spent some time getting more up to speed on APT and then discovering that JSR269 exists, does anyone know if JSR269 will provide the facility to generate output to overwrite the input source file? Because that would make this sort of useful code bending annotation API applicable.

                  Bean.java -> javac -> Bean.java -> javac -> Bean.class

                  APT and 269 can both recursively process files, but I don't think APT can overwrite any of its input files (could well be wrong here).

                  If 269 can do that, then I can't wait!
                  • 6. Re: Generate getter/setter methods with annotations?
                    843793
                    "The problem with all these approaches, however, is that because they don't produce the class additions until runtime, you're stuck working with reflection to get at the new methods - which is probably more hassle than just creating them from scratch in the source code in the first place."

                    Not sure I see the problem. Runtime generation of getter/setter methods would change very little, I think. The (only) alternative to reflection is to parse the source file directly, no? I doubt that anyone would prefer parsing the source file to reflection for the purpose of figuring out class' properties/methods... that would be almost as difficult as writing your own javac!
                    • 7. Re: Generate getter/setter methods with annotations?
                      dcminter
                      Not sure I see the problem. Runtime generation of
                      getter/setter methods would change very little, I
                      think.
                      My point being that ONLY reflection would be available to you. Which is not the case if you create them at the source level.

                      I.e.
                      Foo foo = new Foo();
                      foo.setBar("bar"); // Not allowed.
                      • 8. Re: Generate getter/setter methods with annotations?
                        843793
                        foo.setBar("bar"); // Not allowed.
                        Yes, you're right. To do that would require changes in javac and perhaps JVM. Should've been done long time ago though, it's worth it, in my opinion.
                        • 9. Re: Generate getter/setter methods with annotations?
                          dcminter
                          To do that would require changes in
                          javac and perhaps JVM.
                          Only in Javac - and JSR269 looks like it gets you at least halfway there, since it allows you to hook into the compiler, effectively. But unfortunately it doesn't look like it lets you muck around with the definition of the class that it's processing, only spit out new class source/binaries for further compilation/processing.
                          • 10. Re: Generate getter/setter methods with annotations?
                            608410
                            Thats right,

                            You cannot change the source code that is being processed, either with apt or with JSR 269.

                            See http://blogs.sun.com/roller/page/gbracha?entry=annotations_toward_pluggable_types
                            for some reasons why.

                            You CAN generate new classes, and in this case (properties) your best options are either generating a subclass or superclass.

                            However, when you do that, the weight of the baggage is probably more than the value you gain from it.

                            So a better strategy might be to approach it from the IDE side. Some ideas for improvements
                            - generated accessors should be 1 liners (not nicely formatted) (reduces vertical clutter)
                            - you could annotate fields with @Property as an alternative way of telling the IDE to generate the accessors.
                            - the IDE could collapse (minimal) accessors (those with the trivial implementation)
                            • 11. Re: Generate getter/setter methods with annotations?
                              843793
                              > So a better strategy might be to approach it from the IDE side.

                              I really think Sun should change javac (+JVM?) so public getter/setter methods are added at run-time. It could be some @Auto-getter-setter tag or some new access scope modifier private-pgs or whatever... my impression is it could be easily done.

                              Comparing this feature to other JSE5 syntax sugar like Autoboxing/Unboxing and Enhanced for Loop, it could be a real help. Can we get it in JSE6? Thanks!
                              • 12. Re: Generate getter/setter methods with annotations?
                                608410
                                Yeah right!!
                                AP739960.java:3: illegal start of type
                                @Auto-getter-setter
                                     ^
                                1 error
                                
                                
                                
                                
                                User.java:4: cannot find symbol
                                symbol  : method getText()
                                location: class AP739960
                                        System.out.println(new AP739960().getText());
                                                           ^
                                1 error
                                • 13. Re: Generate getter/setter methods with annotations?
                                  843793
                                  Comparing this feature to other JSE5 syntax sugar
                                  like Autoboxing/Unboxing and Enhanced for Loop, it
                                  could be a real help. Can we get it in JSE6? Thanks!
                                  Language support for this will not happen in Java SE 6 (Mustang). However, better support for bean getter/setters is a long-standing request that might be addressed in Java SE 7 (Dolphin).
                                  • 14. Re: Generate getter/setter methods with annotations?
                                    843793
                                    Thanks for the response.

                                    > You cannot modify existing source files with
                                    annotation processing.


                                    What about providing the generated getter/setter
                                    methods only at runtime? I do not even have the need
                                    to see the generated gettters/setters at all, the
                                    logic is obvious. Additional classes/subclasses make
                                    the benefits moot.

                                    My whole point of generating getter/setter methods
                                    was to make the source code cleaner and, as a result,
                                    simpler and easier to maintain. Completely dumb,
                                    obvious getter/setter method logic occupies
                                    thousands lines of code in our company's
                                    projects, cluttering the real logic with noise. It
                                    also take some time to create AND maintain all those
                                    getter/setter methods (yes, IDE helps but still...)
                                    1 2 Previous Next