How can I create implementations of an interface dynamically at runtime in java?
I have a factory that will read the annotations on class Foo and create an instance of class Bar. For this factory to be type safe, I’d like my client factories to be interfaces with a factory method that takes type Foo and returns type Bar. I then want my factory to implement this factory method at runtime.
All of this is because the factory code would be redundant and hard to maintain. If generated at runtime, it would always be current.
Example:
public class Foo{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
public class Bar{
private String personName;
public String getPersonName(){
return personName;
}
public void setPersonName(String personName){
this.personName= personName;
}
}
public interface BarFactory{
Bar create(Foo foo);
}
Is there a way to do this?
Use Java Proxy reflection. See examples here: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html