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..
9 43652 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. - Class c = Class.forName("myClass");
-
for (i=1; ....)
-
{
-
Field f = c.getField("var" + i);
-
f.setInt(this, i);
-
}
(code not yet tested, but I hope you get the idea.)
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. - Class c = Class.forName("myClass");
-
for (i=1; ....)
-
{
-
Field f = c.getField("var" + i);
-
f.setInt(this, i);
-
}
(code not yet tested, but I hope you get the idea.)
The idea I get is that this would be a spectacularly bad idea!
-
1. Class c = Class.forName("myClass");
-
2. for (i=1; ....)
-
3. {
-
4. Field f = c.getField("var" + i);
-
5. f.setInt(this, i);
-
6. }
-
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?
- package org.struts.ets.utility;
-
-
import java.lang.reflect.Constructor;
-
import java.lang.reflect.InvocationTargetException;
-
import java.util.ArrayList;
-
import java.util.List;
-
-
import org.struts.bean.GenericDAOBean;
-
-
public class DynamicObjectCreation
-
{
-
public static void main(String... args)
-
{
-
Constructor[] ctors = GenericDAOBean.class.getDeclaredConstructors();
-
Constructor ctor = null;
-
for (int i = 0; i < ctors.length; i++)
-
{
-
ctor = ctors[i];
-
if (ctor.getGenericParameterTypes().length == 2)
-
break;
-
}
-
-
try
-
{
-
ctor.setAccessible(true);
-
-
// This is what is created dynamically and passed to the
-
// action class
-
Object myObj1 = ctor.newInstance("A", "B");
-
Object myObj2 = ctor.newInstance("C", "D");
-
List<Object> myObjList = new ArrayList<Object>();
-
myObjList.add(myObj1);
-
myObjList.add(myObj2);
-
-
// the action class casts into the object type it needs
-
GenericDAOBean myGenObj = (GenericDAOBean) myObjList.get(0); // myObj1
-
// Field f = c.getClass().getDeclaredField("var1");
-
// f.setAccessible(true);
-
// System.out.println("output: " + f.get(c).toString());
-
System.out.println("output: " + myGenObj.getVar1());
-
-
// passing a list of these generic objects
-
List<GenericDAOBean> myGenObjList = new ArrayList<GenericDAOBean>();
-
myGenObjList = (myGenObjList)myObjList;
-
-
// production code should handle these exceptions more gracefully
-
} catch (InstantiationException x)
-
{
-
x.printStackTrace();
-
} catch (InvocationTargetException x)
-
{
-
x.printStackTrace();
-
} catch (IllegalAccessException x)
-
{
-
x.printStackTrace();
-
}
-
}
-
}
See that this is where I have the problem, - List<GenericDAOBean> myGenObjList = new ArrayList<GenericDAOBean>();
-
// or
-
// List<GenericDAOBean> myGenObjList = null;
-
-
myGenObjList = (myGenObjList)myObjList;
It says myGenObjList cannot be resolved to a type
BigDaddyLH 1,216
Recognized Expert Top Contributor - myGenObjList = (myGenObjList)myObjList;
For casting, what goes in the parentheses must be a type, not a variable.
...
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: - Class c = Class.forName("myClass");
-
Field[] f = c.getFields();
-
for (int i=0; i < f.length; i++)
-
{
-
...
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.
Here is a very hard-coded alternative to your problem:
1) Create an interface with value setter -
public interface RowWithColumnValues {
-
void setColumnValue(int columnId, String value);
-
}
-
2) Hard-code part: create classes that implement the interface above with exactly 1"escalating " variable and extending the "previous" variable's class: -
public class RowWithColumn1 implements RowWithColumnValues {
-
-
public String column1;
-
-
public void setColumnValue(int columnId, String value)
-
{
-
if(columnId == 1)
-
column1= value;
-
}
-
}
-
-
-
public class RowWithColumn2 extends RowWithColumn1 {
-
-
public String column2;
-
-
public void setColumnValue(int columnId, String value)
-
{
-
if(columnId == 2)
-
column2 = value;
-
else
-
super.setColumnValue(columnId, value);
-
}
-
}
-
-
-
public class RowWithColumn3 extends RowWithColumn2{
-
-
public String column3;
-
-
public void setColumnValue(int columnId, String value)
-
{
-
if(columnId == 3)
-
column3 = value;
-
else
-
super.setColumnValue(columnId, value);
-
}
-
}
-
-
-
//etc, yes, you have to make as much classes as your possible maximum number of variables
-
3) Create a Factory that will return you the proper class with variables -
public RowWithColumnValues getRowObject(int numberOfColumns)
-
{
-
RowWithNodes rowObject = null;
-
switch(numberOfColumns)
-
{
-
case 1: rowObject= new RowWithColumn1(); break;
-
case 2: rowObject= new RowWithColumn2(); break;
-
case 3: rowObject= new RowWithColumn3(); break;
-
//....
-
case 100: rowObject= new RowWithColumn100(); break;
-
default: rowObject= new RowWithColumn100(); break;
-
}
-
-
return rowObject;
-
}
-
Now, you can use this as: -
RowWithColumnValues row= new RowWithColumnValues().getRowObject(numOfColumns);
-
// set column values
-
for(int i = 1; i < numOfColumns+1; i++)
-
{
-
row.setColumnValue(i, rs.getString(i));
-
}
-
rows.add(row);
-
-
A bit more clearer explanation is given at http://djamshed.blogspot.com/2008/03...r-dynamic.html
Thanks Jamshed,
I am looking into it and also going through your blog entry. Will get back to you soon.
-Cheers
Krishna
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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>
|
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
|
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
|
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
| |
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
|
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
|
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
|
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...
|
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,...
|
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...
| |
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...
|
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...
|
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();...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |