I have ended up in a situation, where I can use reflection to get a Constructor object and then using that Constructor to instantiate a class or I can use Constructor reference to instantiate it. I wanted to know which is better in terms of performance. I know accessing a method with reflection gives low performance than accessing it directly, but if I use Constructor reference then it should create a dynamic anonymous type to get the instance I wanted. Which is better Reflection or Method reference?
interface ConstructorRef {
public abstract Component getInstance();
}
class Component1 implements Component {
}
class Main {
public static void main(String[] args) {
ConstructorRef reference = Component1::new;
Component component = reference.getInstance();
Class<? extends Component> classObj = Component1.class;
Constructor<? extends Component> constructorObj = classObj.getConstructor();
Component component1 = constructorObj.getInstance();
}
}
Actually there is so many Components and I will only know which component to instantiate at runtime, The number of components will grow as new requirements come. So, I am restricted to use one of the above methods I can't use direct object instantiation using new operator. So, which is better among the two alternatives?
Aucun commentaire:
Enregistrer un commentaire