Ankit Agarwal
Ankit Agarwal

Reputation: 124

Java Create instance of class using Annotation

I am trying to create a instance of class using annotation.Lets say I have two subclass from parent class

public class Parent{

}

@(type = abc)
public class Child1 extends Parent{


}

@(type = def)
public class Child2 extends Parent{


}

Now, I want a method which will return the instance of class child1 when I pass "abc" and instance of class child2 when I pass "def". Is it possible using annotation.

Upvotes: 1

Views: 932

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533462

You need to traverse all the classes and find those with the annotation of interest. You can then create an index of "type" to class, so you can look it up later to determine which class to create.

You can use the Reflections library to find all the class which have an annotation.

Upvotes: 1

Related Questions