473,395 Members | 2,795 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to create and initialize dynamic variables...

How to create dynamic variables as follows

for(...)
{
Run This( "int var" + i = i;);
}

to be able to create and initialize var1 = 1; var2 = 2;

I was able to do this in a couple of scientific programming languages without any problem..

Help please..
Feb 20 '08 #1
9 43452
BigDaddyLH
1,216 Expert 1GB
Easily done with a Map.
Feb 20 '08 #2
chaarmann
785 Expert 512MB
You should do it with arrays/maps instead of using a couple of loose variables.

Defining "int[] vars" is better than using "var1, var2, var3 etc."

But if you still want, despite all experience:
you can define "public static Integer var1, var2 etc" as member of a class and then use "reflection" to modify the values of this class in a loop.

Expand|Select|Wrap|Line Numbers
  1. Class c = Class.forName("myClass");
  2. for (i=1; ....)
  3. {
  4.   Field f = c.getField("var" + i);
  5.   f.setInt(this, i);
  6. }
(code not yet tested, but I hope you get the idea.)
Feb 20 '08 #3
BigDaddyLH
1,216 Expert 1GB
You should do it with arrays/maps instead of using a couple of loose variables.

Defining "int[] vars" is better than using "var1, var2, var3 etc."

But if you still want, despite all experience:
you can define "public static Integer var1, var2 etc" as member of a class and then use "reflection" to modify the values of this class in a loop.

Expand|Select|Wrap|Line Numbers
  1. Class c = Class.forName("myClass");
  2. for (i=1; ....)
  3. {
  4.   Field f = c.getField("var" + i);
  5.   f.setInt(this, i);
  6. }
(code not yet tested, but I hope you get the idea.)
The idea I get is that this would be a spectacularly bad idea!
Feb 20 '08 #4
Expand|Select|Wrap|Line Numbers
  1.    1. Class c = Class.forName("myClass");
  2.    2. for (i=1; ....)
  3.    3. {
  4.    4. Field f = c.getField("var" + i);
  5.    5. f.setInt(this, i);
  6.    6. }
  7.  
This is exactly what I thought of initially. The problem with this code really is that you need to know the field names, type of variables that you are setting aprior as in f.setInt(this,i)
and I have to initialize different number and type of fields.

So I thought I could create a string equivalent

List<someObjectName> myList;
myList.add(someObjectName(var1, var2, var3,....))


Let me first explain my actual problem in detail first:

I have a dynamically created query that is run on the database and we have the result set columns which can be used to initialize a known object. These objects (type not known) with constructors have to be populated dynamically. Essentially a list of these objects must be passed to some table in a jsp for display purposes. The jsp page dynamic tag libraries only accepts bean/objects.

As an awkward solution to this, we tried a genericBean object with 10 string fields in it and hence the object has a constructor with 10 fields, a maximum number of fields we might have to display in the jsp table. As different queries return different number of columns (converted to string equivalents), the remaining fields in the constructor are set as empty strings. At the jsp page, we control how many columns we want to display in the jsp from this list of objects.

Is there a solution to this problem?
Feb 21 '08 #5
Expand|Select|Wrap|Line Numbers
  1. package org.struts.ets.utility;
  2.  
  3. import java.lang.reflect.Constructor;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import org.struts.bean.GenericDAOBean;
  9.  
  10. public class DynamicObjectCreation
  11. {
  12.     public static void main(String... args)
  13.     {
  14.         Constructor[] ctors = GenericDAOBean.class.getDeclaredConstructors();
  15.         Constructor ctor = null;
  16.         for (int i = 0; i < ctors.length; i++)
  17.         {
  18.             ctor = ctors[i];
  19.             if (ctor.getGenericParameterTypes().length == 2)
  20.                 break;
  21.         }
  22.  
  23.         try
  24.         {
  25.             ctor.setAccessible(true);
  26.  
  27.             // This is what is created dynamically and passed to the
  28.             // action class
  29.             Object myObj1 = ctor.newInstance("A", "B");
  30.             Object myObj2 = ctor.newInstance("C", "D");
  31.             List<Object> myObjList = new ArrayList<Object>();
  32.             myObjList.add(myObj1);
  33.             myObjList.add(myObj2);
  34.  
  35.             // the action class casts into the object type it needs
  36.             GenericDAOBean myGenObj = (GenericDAOBean) myObjList.get(0); // myObj1
  37.             // Field f = c.getClass().getDeclaredField("var1");
  38.             // f.setAccessible(true);
  39.             // System.out.println("output: " + f.get(c).toString());
  40.             System.out.println("output: " + myGenObj.getVar1());
  41.  
  42.             // passing a list of these generic objects
  43.             List<GenericDAOBean> myGenObjList = new ArrayList<GenericDAOBean>();
  44.             myGenObjList = (myGenObjList)myObjList;
  45.  
  46.             // production code should handle these exceptions more gracefully
  47.         } catch (InstantiationException x)
  48.         {
  49.             x.printStackTrace();
  50.         } catch (InvocationTargetException x)
  51.         {
  52.             x.printStackTrace();
  53.         } catch (IllegalAccessException x)
  54.         {
  55.             x.printStackTrace();
  56.         } 
  57.     }
  58. }
See that this is where I have the problem,

Expand|Select|Wrap|Line Numbers
  1. List<GenericDAOBean> myGenObjList = new ArrayList<GenericDAOBean>();
  2. // or 
  3. // List<GenericDAOBean> myGenObjList = null;
  4.  
  5. myGenObjList = (myGenObjList)myObjList;
It says myGenObjList cannot be resolved to a type
Feb 21 '08 #6
BigDaddyLH
1,216 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. myGenObjList = (myGenObjList)myObjList;
For casting, what goes in the parentheses must be a type, not a variable.
Feb 21 '08 #7
chaarmann
785 Expert 512MB
...
The problem with this code really is that you need to know the field names, type of variables that you are setting aprior as in f.setInt(this,i)
and I have to initialize different number and type of fields.
...
There is no need to "know" the field names in advance. You can just enumerate them.
For example:
Expand|Select|Wrap|Line Numbers
  1. Class c = Class.forName("myClass");
  2. Field[] f = c.getFields();
  3. for (int i=0; i < f.length; i++)
  4. {
  5.  ...
Just look in the JDK description for all methods of class "Class".
You can get all information about the class there, also skope, field types, methods, method parameters etc.

But if you only want to pass data, then you can just declare the method parameter as "Object" and pass it. Then you can test with "instanceOf" which type it is. But that also means you must do some inboxing/outboxing for primitive types. Then for example you cannot store an integer as "int", but must convert it to "Integer" before passing.

Second suggestion: if you already have converted all table column values to "String", then you can use "Properties" to store them in a manner of key=variableName, value=variableValue. No need to hardcode a fixed size array as what you described in your example.
If you have more than one record(row) returned from database, you can use "Vector" of "Properties" and pass/return that as argument/returnValue to your functions.
Feb 23 '08 #8
Here is a very hard-coded alternative to your problem:
1) Create an interface with value setter
Expand|Select|Wrap|Line Numbers
  1.      public interface RowWithColumnValues {
  2.              void setColumnValue(int columnId, String value);
  3.     }
  4.  
2) Hard-code part: create classes that implement the interface above with exactly 1"escalating" variable and extending the "previous" variable's class:

Expand|Select|Wrap|Line Numbers
  1.  public class RowWithColumn1 implements RowWithColumnValues {
  2.  
  3.       public String column1;
  4.  
  5.      public void setColumnValue(int columnId, String value)
  6.      {
  7.            if(columnId == 1)
  8.            column1= value;
  9.      }
  10. }
  11.  
  12.  
  13. public class RowWithColumn2 extends RowWithColumn1 {
  14.  
  15.       public String column2;
  16.  
  17.       public void setColumnValue(int columnId, String value)
  18.       {
  19.             if(columnId == 2)
  20.                  column2 = value;
  21.             else
  22.                   super.setColumnValue(columnId, value);
  23.       }
  24. }
  25.  
  26.  
  27. public class RowWithColumn3 extends RowWithColumn2{
  28.  
  29.       public String column3;
  30.  
  31.       public void setColumnValue(int columnId, String value)
  32.       {
  33.             if(columnId == 3)
  34.                   column3 = value;
  35.             else
  36.                   super.setColumnValue(columnId, value);
  37.       }
  38. }
  39.  
  40.  
  41. //etc, yes, you have to make as much classes as your possible maximum number of variables
  42.  
3) Create a Factory that will return you the proper class with variables
Expand|Select|Wrap|Line Numbers
  1. public RowWithColumnValues getRowObject(int numberOfColumns)
  2. {
  3.          RowWithNodes rowObject = null;
  4.          switch(numberOfColumns)
  5.          {
  6.                   case 1: rowObject= new RowWithColumn1(); break;
  7.                   case 2: rowObject= new RowWithColumn2(); break;
  8.                   case 3: rowObject= new RowWithColumn3(); break;
  9.                   //....
  10.                   case 100: rowObject= new RowWithColumn100(); break;
  11.                   default: rowObject= new RowWithColumn100(); break;
  12.          }
  13.  
  14.          return rowObject;
  15. }
  16.  


Now, you can use this as:

Expand|Select|Wrap|Line Numbers
  1. RowWithColumnValues row= new RowWithColumnValues().getRowObject(numOfColumns);
  2. // set column values
  3. for(int i = 1; i < numOfColumns+1; i++)
  4. {
  5.         row.setColumnValue(i, rs.getString(i));
  6. }
  7. rows.add(row); 
  8.  
  9.  
A bit more clearer explanation is given at http://djamshed.blogspot.com/2008/03...r-dynamic.html
Mar 18 '08 #9
Thanks Jamshed,

I am looking into it and also going through your blog entry. Will get back to you soon.

-Cheers
Krishna
Mar 24 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Tommy Lang | last post by:
Hi everybody! I am trying to learn the basics of C++ myself and have a hard time understanding some stuff like pointers and references etc. I have created a small program that adds two numbers...
1
by: Tommy Lang | last post by:
I am trying to learn to use dynamic variables. I have pasted the code below. Is this the proper way of using dynamic variables? Thanks, Tommy ...
18
by: vib | last post by:
Hi there, By chance, I came to learn that it is bad programming practice to initialize global variables at outside of programs. Is it that bad? In order to fullfil this, I had to declare them...
0
by: TJS | last post by:
trying to use code below to create dynamic variables but no success, what an I missing ? -------------------------- for i = 0 to 2 dim vString as string = "Dim submenu" & Cstr(i) & " As New...
28
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. ...
12
by: scott | last post by:
Is there a way to create dynamic variables when looping through a recordset? For example below, after the 1st loop I'd have myVarA1 and myVarB1, after 2nd loop, I'd get myVarA2 and myVarB2. CODE...
4
by: Mr. Smith | last post by:
Hi. What's the correct syntax here: (given the recordset myRS with x records do until myRS.EOF txtvar & myRS("serial_number") = myRS("serial_name") myRS.movenext loop ..asp will not build...
1
by: andrebarn | last post by:
Hi guys I what to create Dynamic variables when I loop through and recordset, I have read this forum : http://bytes.com/forum/thread436288.html But see my problem is that so af the variables need...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.