1

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.

Rajat Sharma
  • 502
  • 4
  • 8
  • 17
  • http://stackoverflow.com/questions/9886266/is-there-a-way-to-instantiate-a-class-by-name-in-java – Asterisk Dec 13 '13 at 07:22
  • putting a comment here after some 4 years just in case someone lands up. Fragments should never be instantiated with a constructor. see http://stackoverflow.com/questions/14654766/creating-a-fragment-constructor-vs-newinstance. For a generic class loading by name, reflection is the way. see Asterisk's comment above. – Rajat Sharma Mar 03 '17 at 07:29

1 Answers1

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.newInstance();
epoch
  • 16,396
  • 4
  • 43
  • 71