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
  • 13,563
  • 15
  • 74
  • 125

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,924
  • 4
  • 40
  • 58
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
  • 33,938
  • 5
  • 80
  • 91
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,975
  • 2
  • 18
  • 37
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,250
  • 16
  • 23