0

This is kind of complicated, but I need to have my program to be able to detect, which class to reference based on the data of an array.

I know how to do this by using a huge if statement, but that would be a HUGE amount of code. Is there a way to like put the variable so that it would be like
String x; x new = new x();
if you get the idea. x would hold the class name. Or is there another way to do this? Thanks.

2
  • 3
    Use reflection. It's not exactly fixed the way you are describing though... Commented Sep 19, 2013 at 21:03
  • 1
    This feels like an XY problem/question .. can you explain the task better? This desired approach cannot work in a static-typed manner as envisioned. The "best" that could be done based on a stricter interpretation of the question is: Object x = CreateInstanceOfSomeTypeDynamically(str) or similar. Note that this results in 1) a fixed variable name (x) and 2) not a very useful type refinement on said variable (an interface of supertype could unify a bit, but it feels like an XY problem). Commented Sep 19, 2013 at 21:07

1 Answer 1

5

You should use Java Reflection for this. Here's a link to the tutorials. This one will be the most relevant. Here's an example of what you can do:

String x = ...
Class c = Class.forName(x);
X x = c.newInstance()
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.