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.
}
}
}
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.
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");
The java. lang and java. lang. reflect packages provide classes for java reflection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With