Results 1 to 6 of 6
- 08-28-2008, 01:18 PM #1
Member
- Join Date
- Aug 2008
- Posts
- 6
- Rep Power
- 0
Creating and using java objects at runtime...
Hi,
I am looking for something like this...
If I pass the name of the class and the name of the variable as string, I need a method that is able to create the class object and assign a value to the attribute a particular value..
e.g. something like below method:
public Object method(String className, String attributeName){
String attributeValue="testData"
className.attributeName = attributeValue;
return className;
}
So far I am able to create a class from string and also am able to identify the name of the attributes available in the class, but not sure how we can achieve the above thing in java..
Any help would be appreciable.
- 08-28-2008, 01:47 PM #2
Look at the reflection package and the Class class. They have methods to create objects from existing class definitions and to access methods and fields in those objects.
Returning the variable className doesn't make sense here. You've defined it to be a String. The String class does NOT have a field named attributeName.public Object method(String className, String attributeName){
String attributeValue="testData"
className.attributeName = attributeValue;
return className;
}
The syntax of using the reflection package classes and methods is different, but they will allow you to access public fields in an object by a name given as a String. Specifically look at the Field class.
- 08-28-2008, 03:08 PM #3
Member
- Join Date
- Aug 2008
- Posts
- 6
- Rep Power
- 0
Hi,
thanks for the reply, you are right...i should have mentioned....(object)className in the return section...I ll take a look at it...and see if it helps
- 08-28-2008, 03:41 PM #4
casting it to Object is not going the change it from being a String.
The method will return the String that was passed as an arg unless you assign a new value to className in the method.
- 08-28-2008, 05:30 PM #5
- 08-28-2008, 05:36 PM #6
Similar Threads
-
Creating an Array of Objects
By int80 in forum New To JavaReplies: 4Last Post: 08-09-2011, 12:40 PM -
Creating objects based on a String value
By lvh in forum New To JavaReplies: 4Last Post: 04-30-2008, 02:00 PM -
Creating an array of nonprimitive objects
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:46 PM -
Creating objects question
By sergm in forum New To JavaReplies: 2Last Post: 12-27-2007, 04:10 PM -
creating array at runtime
By javaplus in forum New To JavaReplies: 4Last Post: 11-08-2007, 10:06 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks