2

I have classes that are automatically generated in Java. I want to add a method to that class (in another file) so that I can add additional functionality without changing the generated file. The idea being that if I have to recreate the generated file, I won't lose my new functionality.

In Objective-c I know this is called categories, and in JavaScript you can append the object's prototype, but I am unaware of how to do this in Java or what it is called.

Jason
  • 12,288
  • 14
  • 67
  • 121

4 Answers4

3

This is not supported in java.

partial classes/partial class file

One thing you can do is inherit the generated class (if it is not final) and add your methods.

Community
  • 1
  • 1
Itay Karo
  • 17,370
  • 4
  • 38
  • 56
1

You could just use composition, ie:

public class JasonString {
   String wrapped;

   public JasonString() {
      wrapped = new String();
   }

   public String toString() {
      return wrapped.toLowerCase().toString();
   }

   // other methods of wrapped class you're using should just call the corresponding method in wrapped.
}
hd1
  • 32,598
  • 5
  • 75
  • 87
0

If you do not have access to the generated class you could try to extend it (if generated class is not final) and add new methods to sub-class... Java doesn't support dynamic attributes as JavaScript.

nkukhar
  • 1,935
  • 2
  • 16
  • 36
0

I agree with @Itay I used to have auto-generated classes from Ibatis and the best way to go about with your problem is to extend all the generated classes and add the functionality that you want.

Ankit
  • 1,220
  • 16
  • 23