Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new method to a class through reflection [duplicate]

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.

        }
    }
}
like image 724
Tapas Jena Avatar asked May 10 '13 15:05

Tapas Jena


People also ask

How do you create an instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

How do you reflect a class in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

Which package is used for reflection?

The java. lang and java. lang. reflect packages provide classes for java reflection.


1 Answers

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.

like image 69
Boris the Spider Avatar answered Oct 11 '22 07:10

Boris the Spider