2

ok so this has been asked many times and I have looked at various answers but still somehow not able to get this right.

Problem: I have some 5 fragments(non android guys please assume classes) which I need to dynamically instantiate based on what is clicked in a list. I get the string in the click handler. I have named my fragments conveniently. So basically one of my fragments is called SearchResults.java and the corresponding item click will return "SearchResults". So I want to do something like:

public void onClick(View v) {
Class cls = Class.forname(clickedString)   //clickedString = "SearchResults"
//instantiate it as if it were equal to SearchResults sr = new SearchResults().
}

I just want to avoid if/ else or switch cases and looking for a smarter way. I might be missing some very basic core java concepts. Please help.

2

1 Answer 1

1

Firstly you need fully qualified class names, i.e: your.full.class.path.SearchResults, after that it becomes relatively easy to instantiate assuming a no-args constructor:

Class<?> cls = Class.forName(clickedString);
SearchResults results = (SearchResults) cls.getDeclaredConstructor().newInstance();

Both newInstance() and getDeclaredConstructor() optionally take in the argument and argument types respectively.

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

5 Comments

so you mean clickedString has to be a fully qualified classname? And as luck would have it, my fragments already have a newInstance method. More of a factory thing. Hope that is called and not the default one.
It would work for me I guess. Except that my fragments already have a static 'newInstance' method.
The method is called forName not forname.
newInstance() is deprecated since version 9. What is the current way to do this?
@RichardNeumann Class.newInstance is deprecated as it bypasses constructor code. But Constructor.newInstace is fine.

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.