views:

110

answers:

4

Hi I have the following requirement.

I want to create variable number of String arrays in a method, based on the number of levels present. For e.g

I have the variable numOfLevels (int) received from a jsp page.

Based on this I want to create:

String[] level1;
String[] level2;
String[] level3;
String[] level4;

etc ...

I know my requirement can be handled with Hashmaps and I've finally resorted to doing that, but I'm curious as to how this can be achieved with reflection in Java.

Many thanks in advance.


Hmm like a commenter pointed out, an almost similar question was asked at http://stackoverflow.com/questions/1192534/is-there-away-to-generate-variables-names-dynamically-in-java/1192561

Thanks for the valuable inputs people!

A: 

http://java.sun.com/developer/technicalArticles/ALT/Reflection/

SUMMARY: Using Arrays One final use of reflection is in creating and manipulating arrays. Arrays in the Java language are a specialized type of class, and an array reference can be assigned to an Object reference.

adatapost
+3  A: 

Reflection can only show you what is, it can't change it (just like a mirror can only show what it reflects; changes to the mirror won't change the original object).

To change a class, you need to modify the bytecode. There are libraries for that (cglib) but it's not for the faint of heart. In your case, a map is the correct solution.

Aaron Digulla
+6  A: 

Static languages cannot declare variables at runtime.

What you might want to use is an array of arrays

String[][] level = new String[numOfLevels][];

level[0] = ...
level[1] = ...
level[2] = ...
level[3] = ...
Adrian
A: 

I think this is the same question as is-there-away-to-generate-variables-names-dynamically-in-java

The winner was

use the Java Scripting API

Markus Lausberg