473,662 Members | 2,551 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to create and initialize dynamic variables...

25 New Member
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 43652
BigDaddyLH
1,216 Recognized Expert Top Contributor
Easily done with a Map.
Feb 20 '08 #2
chaarmann
785 Recognized Expert Contributor
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 Recognized Expert Top Contributor
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
krishna81m
25 New Member
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<someObject Name> myList;
myList.add(some ObjectName(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
krishna81m
25 New Member
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 Recognized Expert Top Contributor
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 Recognized Expert Contributor
...
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=variableNam e, value=variableV alue. 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
djamshed
1 New Member
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
krishna81m
25 New Member
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
8403
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 and prints the result on the screen. The program works just fine and I am proud of it :). But now I want to make some changes to it and only use dynamic variables (and make use of *, &, new...). I know from books that you create dynamic variables...
1
2238
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 //------------------------------------------------------------ #include <iostream>
18
8638
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 with const, but thereafter they are no longer variables. Just couldn't see the benefits of this practice. Any comments or advices are welcome. Thanks vib
0
839
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 skmMenu.MenuItem(" & tab.TabName & ", """")" EXECUTE (vString) next
28
4611
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. Would the performance be better using Static versus Dynamic. I would think it would be quicker with STATIC declarations since the variables would only have to be created once. Can anyone confirm this. Thanks. -- Dennis in Houston
12
6242
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 *********************************** set objRS = GetMyRecordSet() i=1 objRS.MoveFirst
4
2419
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 the dynamic variables
1
1876
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 to be an array. Example: Dim ObjParmArr Dim ArrayCounter Dim i Dim ParmList
0
8432
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8344
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8857
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8633
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7367
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5654
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.