10

Is it possible to add a method to a class through reflection in java??

public class BaseDomain {

    public BaseDomain(){
        Field[] fields = this.getClass().getDeclaredFields();
        for(int i=0; i<fields.length; i++){
            String field = fields[i].toString();

            String setterMethod = "public void set" + field.toLowerCase();

            //Now I want to add this method to this class.

        }
    }
}
Tapas Jena
  • 1,069
  • 4
  • 14
  • 23
  • 2
    http://stackoverflow.com/questions/6680674/can-a-java-class-add-a-method-to-itself-at-runtime – zw324 May 10 '13 at 15:15
  • What is the *actual problem* that you're trying to solve. There is probably an easier way to implement it. – parsifal May 10 '13 at 15:22
  • This is what I want.....http://stackoverflow.com/questions/16482686/adding-getters-setters-to-one-base-class – Tapas Jena May 10 '13 at 15:25
  • @Tapas That doesn't add a new method. It just allows you to set a field through reflection. – Sotirios Delimanolis May 10 '13 at 15:41
  • @TapasJena - you want to automatically generate getters and setters? Your IDE does that, with far less effort than it will take you to implement an external solution. – parsifal May 10 '13 at 18:58
  • Not exactly....I am searching for a solution like http://projectlombok.org . The problem with this library is It is forcing developer to install a plugin on IDE(Eclipse, Netbeans etc) which I cann't afford as I want this feature in a webframework. – Tapas Jena May 10 '13 at 19:30

2 Answers2

13

No, not through reflection.

Reflection asks about classes and their members, you can change fields but you cannot create new ones. You cannot add new methods.

You can use a a bytecode manipulation library to add methods to classes; but why would you want to?

You can't call the methods anyway except via reflection as they would obviously not exist at compile time.

Maybe take a look at project Lombok - this is a annotation preprocessor that can add methods to classes at compile time. It will add getters and setters automagically as long as your classes are correctly annotated.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • To add to Boris' answer, remember that you are using a statically typed language. If you want something more dynamic then look into ruby or python – cmbaxter May 10 '13 at 15:17
  • 1
    @Boris.....Pls check my previous post. http://stackoverflow.com/questions/16482686/adding-getters-setters-to-one-base-class – Tapas Jena May 10 '13 at 15:24
  • @TapasJena that question was about compile time generics this question is about runtime reflection - they aren't really related. – Boris the Spider May 10 '13 at 15:26
  • I want a compile time solution so that developers can use it as normally with full IDE support....Any idea?? BTW...that post was mine. – Tapas Jena May 10 '13 at 15:33
0

No. You can't add methods through reflection. In this case, I'll use a scripting language like Beanshell 2. Here's a DynamicObject class

public class DynamicObject
{

    bsh.Interpreter interpreter = null;

    public DynamicObject()
    {
        interpreter = new bsh.Interpreter();
    }

    public void addToSource(String... method)
    {
        try
        {
            String main = "";
            for (int i=0; i<lines.length; i++){
                main += lines[i] + "\n";
            }
            interpreter.eval(main);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public Object invoke(String methodname, Object... args)
    {
        try
        {
            return interpreter.getNameSpace().invokeMethod(methodname, args, bsh);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public Object invoke(String methodname)
    {
        return invoke(methodname, (Object[])null);
    }

}

Now an example dynamic object will look like

DynamicObject testObj = new DynamicObject();

testObj.addToSource(

    "public int add ( int a, int b )",
    "{",
        "return a+b;",
    "}"

);

int added = testObj.invoke( "add", 5, 4 );   // is 9
Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91