0

I have a seemingly simple question that I have not been able to find a solution in about a week of searching, so I thought I'd ask. I want to take an array value, say anArray[1] and set it equal to a variable in another class... otherClass.variableOne

This is easy to do, but I want to be able to use a variable for the name of the class i want the variable from. So instead of "otherClass.variableOne" i want something like:

String classVar = "otherClass";    
anArray[1]=classVar.variableOne;

I'm not sure whether i need to set classVar equal to something like... className(otherClass) or something like that. I am quite new to Java and I'm having great difficulty.

I know this seems dumb but it is necessary for what I want to do. I have looked into reflection but it doesn't seem to able to do what I need. Essentially my question is:

String classVar = "otherClass";
anArray[1]=classVar.variableOne

How do i make something like that work where classVar is a variable that refers to a class that contains the public static int variableOne?

Please excuse limited programming experience. Any help is greatly appreciated. Thanks in advance.

2 Answers 2

1

You need to use the Reflection API. You can use it to obtain a Class variable representing "OtherClass" (e.g., Class.forName("com.example.OtherClass") and then go through its fields and methods, and even create new instances of it.

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

Comments

0

I am not sure if i understand your question compeltely, so excuse me if my answer is not useful. If you simply need to assign the value of a public static int variableOne then you can do this by accessing the variable in a static way. Accessing the variable in a static way means simply use the classname.staticVariable to get the variable value. I believe this is what you need:

anArray[1]=OtherClassName.variableOne

replace the ClassName and variableName with your actual classname and variable name.

Read this to understand more about class and instance variables: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

1 Comment

This is what i need to do, but instead of saying 'OtherClassName' i want to use a variable for that. I actually have 33 array values, and therefore if i could just change the variable and make it so that all of the array values would now call the classVariable.variableOne that is preferable.

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.