1

I don't know if this is possible, but what I'd like to know is the following:

Let's say I have an array which contains 2 different class type:

Fruit[] fruit;
fruit[0]= new Banana();
fruit[1]= new Apple();

What I want to do is this:

Fruit unknown= new fruit[0].getClass();

I want to declare an object of a type which is chosen by the user. Can I do it?

Christian Pao.
  • 484
  • 4
  • 13

3 Answers3

4

I presume the user will be saying that they want an "Apple" or a "Banana" i.e. you'll get input as a String. In which case this might be what you need.

Fruit f = (Fruit) Class.forName("Banana").newInstance();
   fruit[0] = f;
Adam Rice
  • 880
  • 8
  • 20
1

Rather than use reflection, consider using a combination of the Factory and Strategy design patterns. Have the input processing code examine the input to see what kind of thing they want, and hence select a Factory/Strategy object. Then, later, when you need the object created, ask the Factory/Strategy object to create it.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
0

It's not very hard -- you are most of the way there. There is a method called newInstance() on the Class interface that you can use like this:

Fruit userFruit = (Fruit) Class.forName(input).newInstance();

(where input is a String containing a class name representing a user's choice) to return a new instance of the type you have.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
  • I had completely messed up my answer, but it was 'accepted' so I've stolen Adam Rice's answer from below simply to make mine right for future readers. Adam deserves the rep for this, but I don't know how to give it to him. – Software Engineer Mar 27 '16 at 17:25
  • Oh, but I actually just needed to know the function newInstance(), since you were the first I accepted yours. – Christian Pao. Mar 27 '16 at 17:56
  • 1
    Yeah, but SO answers are there for future readers too, so should be as correct as possible. – Software Engineer Mar 27 '16 at 18:17