1

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.

4
  • Seems like a factory method is what you need. I don't see where you'd need annotations based on the code you have disclosed. Commented Apr 2, 2015 at 11:30
  • Why do you want to use annotations? If the idea is to return a specific object; depending on the value of some string ... a simple HashMap will do. Commented Apr 2, 2015 at 11:32
  • both the classes above are named the same child1. please correct the typo Commented Apr 2, 2015 at 11:39
  • @(type = def) it will be useless cause "def" must be final. Then it is no difference between call by class name or by annotation argument. Commented Apr 2, 2015 at 11:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.