Converting a String to an Object
Is there some way of converting a String (from a textfield) to an Object? What I want is something similar to the functionality offerred by a JTable. This is because I want the user to be able to input a value of any type to the textfield (e.g. String, int, boolean, etc) and get its object representation ...
Would a simple cast do ?
David
dattard,
A string is an object, when someone enters something into a JTextField, REGARDLESS of what it is (int, double, string, etc) it is stored in the string text in that text field (JTextField.getText()).
So if someone enters in "123", its the STRING 123, not the number one hundred and twenty three... to GET the number 123, you'll need to do something like:
int value = Integer.parseInt( myTextField.getText() );
to have the string parsed for the value, if you want a double, same idea:
double value = Double.parseDouble( myTextField.getText() );
NOTE: The number wrapper classes (Integer, Double, Float, etc.) contain "parseXXXX" methods that allow you to parse a corresponding numeric value out of a String object.
Also, when a user enters ANYTHING into a text input field of any type, its ALWAYS a String, if you want a different version of what they entered, its up to you to parse it and decide what it was.
Similar Messages
-
How to convert a string into an objects name?
Hi
I have the following problem;
I have a string
String a = "e1"
and a method
call(Event e1) that calls the "Event" class with object the name of the string a.
How can I convert the strings name into an object so as to use it in the "call" method?
Any ideas?
Thanks in advanceI don't know if this helps you, but you can do things like this.
String a = "com.example.SomeEvent";
//Instantiate com.example.SomeEvent
Object o = Class.forName(a).newInstance();SomeEvent must have a non-argument constructor for this to work.
Class that will be instantiated depens on runtime value of String a, and can be different across different executions of the program. -
Converting a string to Class object and calling its method
I have recently moved to Java and I need help on this specific issue given below.
I have to do this :
ValModule1 val1 = new ValModule1();
ValModule2 val2 = new ValModule2();
if(val1.checkModule(xmlDocument)){
$i++;
There are many ValModule* classes and they all have the method called checkModule in them. I need to instantiate each class and run the checkMethod which returns true or false. My problem is that I am trying to get the name of the module (if it is ValModule1 or 2 or 3) from the user. What I get from the user is the name of the class for which I should call checkModule method on.
how can I convert this string validationname given by the user and instantiate that class and call the method?
I have tried this:
String str="c:/xpathtest/src/Plugin_Config.xml";
File xmlDocument = new File(str);
String cls = "ValModule1"; // assuming this is what the user gave me
Class t = Class.forName("ValModule1");
Object o = t.newInstance();
After that if I try
if(o.checkModule(xmlDocument)){
$i++;
It gives me an error saying that it is not an existing method
cannot resolve symbol
[javac] symbol : method checkModule (java.io.File)
[javac] location: class java.lang.Object
[javac] if(o.checkModule(xmlDocument)){
[javac] ^
[javac] 1 error
Can you please let me know where I am screwing up :-) ? If you need me to put both the programs I can do that too. Thanks in AnticipationI have recently moved to Java and I need help on this
specific issue given below.
I have to do this :
ValModule1 val1 = new ValModule1();
ValModule2 val2 = new ValModule2();
if(val1.checkModule(xmlDocument)){
$i++;
There are many ValModule* classes and they all have
the method called checkModule in them. I need to
instantiate each class and run the checkMethod which
returns true or false. My problem is that I am trying
to get the name of the module (if it is ValModule1 or
2 or 3) from the user. What I get from the user is
the name of the class for which I should call
checkModule method on.
how can I convert this string validationname given by
the user and instantiate that class and call the
method?
Define an interface containing the method all your classes have in common, cast the Object reference returned by newInstance to that interface, then you can call that method.
Good Luck
Lee -
How can I convert a string to an object or class
I would like to read a file representing a class, and convert it to an object or a class (object preferred). Other postings suggest using javax.tools.JavaCompiler to convert from a string but then say that this is not always available (posting on 1 Jan 09). If this is still not universally available is there another way to do this? If this is not available, are there any examples of how it should be done?
My understanding from what I've read is to read the file into a String then compile the String using javax.tools.JavaCompiler, which is an Interface.
thanksskidmarks wrote:
What i would like to do is to take a Java file representing a class and compile it at runtime. However, the comment about a JDK being available at runtime makes this unattractive.So, you want to compile .java files, but you don't want to have to use a compiler?
The next guess would to be to create a .jar file and reference it at runtime. Here's the scenario:Eh? How is that even remotely equivalent?
1. People using the 'system' will have a varied knowledge of Java.
2. My hope was to require that anyone using the program would only need to create a Java Class file,You mean a Java source file. You have said that YOU want to create the .class file. If they are creating the .class file, then all you need to do is load it with a ClassLoader and start using it.
You might try clarifying your requirements a bit.
In either case, the Class Files would look like:
public class Name {
int field1;
float field2;
} With all the field types being simple Java Primitives.What is the point of this? What are you ultimately trying to accomplish, that can be served by user-defined groups of primitives, with no complex object graphs and no user-defined methods?
Depending on what you're really getting at, using scripting features via beanshell, groovy, or javascript might be an approach to consider, or using Scala to produce a domain-specific language (although I suspect that last may be overkill, and beyond your current skill level).
If this is so, is there any way to create a .jar file at runtime? Do I have to exec("jar") or is there another way.A .jar file is just a .zip file with a manifest. Look at the java.util.jar package. But note that creating a .jar file has nothing to do with the rest of what you're asking about. -
How to convert a string to date object?
I have a string user input for date.
I want to convert it to Date object to insert it in database.
How to do it?Check the java.text.SimpleDateFormat class. You can use it for parsing dates. API contains good description how to build the format pattern.
HTH
Mike -
Convert text string file to object array without outputting to file first?
I have a log file that is just a text string file which is appended to with Out-File. If the log file does not exist I pipe headers to it so that I can import the data as CSV. For example:
DATA.LOG
DATE,TIME,RESPONSE_TIME
05-28-2014, 14:47, 132
05-28-2014, 14:50, 94
05-28-2014, 14:53, 72
I'm using Microsoft Chart Controls to graph the data; it takes it in via CSV format. If I'm going to chart all the entries in DATA.LOG I can simply IMPORT-CSV DATA.LOG. But I only want to graph the 20 most recent entries.
Perhaps there is a better way to do this, but to maintain the header and get the 20 most recent entries I'm using select.
$DATA+=Get-Content .\data.log | select -first 1
$DATA+=Get-Content .\data.log | select -last 20
The problem is $DATA is of type system string so I can't use it directly with Chart Controls; I need to get it in CSV format first. I can Out-File $DATA and then use IMPORT-CSV. But I'd prefer to not have to use
the temporary file. Any suggestions on how I can accomplish this objective?Import-CSV creates an object with the 'header' becoming the named values in the array. The code I posted does the same thing as your 4 lines of code in one line of code:
Much more quickly:
PS C:\temp> (1..1000 | measure-command {import-csv .\data.log | select -last 2}).totalseconds
0.4792951
PS C:\temp> (1..1000 | measure-command {$DATATMP=@();$DATATMP+=Get-Content .\data.log | select -first 1;$DATATMP+=Get-Content .\data.log | select -last 2;ConvertFrom-CSV $DATATMP}).totalseconds
1.6227726
You're more than welcome to use whatever code you want, but if you want to improve your Powershell knowledge you should try to understand the object model around which Powershell is built, it is powerful and efficient.
I hope this post has helped! -
Converting String to an Object of a class
Hi all,
I want to convert a string to an object of a class.
Please see my below code:
MyClass rahul = null;
String data = "DATA";
rahul = (MyClass) data;
I am getting the error: Invalid cast from java.lang.String to MyClass
Please help me as its urgentThere is no magical String deserialization in java. If your class can convert it's state to a string, then you will need to write the reverse parsing code, presumably using either a constructor which takes a string, or a static method similar to how numbers are handled, like:
MyClass c = MyClass.valueOf(data);Obviously, in either case you will need to write the code to do this. -
How to convert a string to date and then compare it with todays date???
Hello.
I want to set a format first for my dates
DateFormate df = new SimpleDateFormate("yyyy-mm-dd");
once this is done then I want to convert any string to date object in the above formate
String str="2001-07-19";
Date d = null;
try{
d = df.parse(s);
}catch(ParseException pe) {
pe.printStackTrace();
First of all there is something wrong above,cus what I get for this is
Fri Jan 19 00:07:00 MST 2001
where as it should have been
2001-07-19... to my understanding.
once this part is done I need to get current date in the above set format and compare the
current date and the date I set.
I will appreciate the help.
Thanksfor the output part:
a date is a point in time
the output depends on the format you specify for output
using for example a SimpleDateFormat.
You only specified the format for parsing (which is independent for that of output) so java uses some default format ... see the DateFormat.format() method for details.
for the comparison stuff, I just posted a little code snippet in this forum a few minutes ago.
the hint is: Date.getTime() returns milliseconds after a fixed date
hth Spieler -
Can I convert a string to a JComponent
If I have a JButton named "exitButton" and I have a String with the text value = "exitButton" is there any way to convert this string into an object that I can then use to perform actions with, for example:
exitButton.isEnable(false);Hi, if you have only a feew buttons/components and there know at compiletime. you can make a vectro containing a keypair containign the string and the button if you don't want to do it this way i believe you can do it using the reflection package it can do taht (i believe) never used it myslef but have a look at the reflection api.
Hope This Helps You,
Robert -
Hi,
I have a problem with an PropertyGrid enum property that uses a type converter.
In general it works, but when I double clicking or using the scoll wheel, an error message appears:
"Property value is not valid"
Details: "Object of type 'System.String' cannot be converted to type 'myCompany.myProject.CC_myCustomProperty."
I noticed that the CommitValue method (in PropertyGridView.cs) tries to convert a string value to a CC_myCustomProperty object.
Here is the code that causes the error (see line 33):
(Using the .net symbols from the PropertyGridView.cs file)
1
internal bool CommitValue(GridEntry ipeCur, object value) {
2
3
Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")");
4
5
int propCount = ipeCur.ChildCount;
6
bool capture = Edit.HookMouseDown;
7
object originalValue = null;
8
9
try {
10
originalValue = ipeCur.PropertyValue;
11
12
catch {
13
// if the getter is failing, we still want to let
14
// the set happen.
15
16
17
try {
18
try {
19
SetFlag(FlagInPropertySet, true);
20
21
//if this propentry is enumerable, then once a value is selected from the editor,
22
//we'll want to close the drop down (like true/false). Otherwise, if we're
23
//working with Anchor for ex., then we should be able to select different values
24
//from the editor, without having it close every time.
25
if (ipeCur != null &&
26
ipeCur.Enumerable) {
27
CloseDropDown();
28
29
30
try {
31
Edit.DisableMouseHook = true;
32
/*** This Step fails because the commit method is trying to convert a string to myCustom objet ***/
33
ipeCur.PropertyValue = value;
34
35
finally {
36
Edit.DisableMouseHook = false;
37
Edit.HookMouseDown = capture;
38
39
40
catch (Exception ex) {
41
SetCommitError(ERROR_THROWN);
42
ShowInvalidMessage(ipeCur.PropertyLabel, value, ex);
43
return false;
44
I'm stuck.
I was wondering is there a way to work around this? Maybe extend the string converter class to accept this?
Thanks in advance,
Eric
Hi,
Thank you for your post! I would suggest posting your question in one of the MS Forums,
MSDN Forums » Windows Forms » Windows Forms General
located here:http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=8&SiteID=1.
Have a great day! -
How Do I Convert a String that Names an Object to a Reference to the Object
You get many program-specific object names in the XML that is returned by describeType. Suppose I find an object that interests me. What is the best way to convert the String that names the object (e.g. the id of the object) to a reference variable that points to the object?
Sure. I am working on a complex application that involves several ViewStacks, several Accordions, some checkboxes, some radio buttons, some text boxes. These components are scattered about, but all are children of a base class that is successfully enumerated by
var classInfo:XML = describeType(vwstk);
Suppose I write a loop as follows:
for each (var a:XML in classInfo..accessor){
Inside that loop I have a series of tests like
if (a.@type == "mx.controls::CheckBox"{
Then, I iterate thru all of the children of the base class as in:
for
(var u:Object in vwstk)
{ if
Inside the if I persist the checked/not checked status of the checkbox.
The tricky part is going from the string a.@name to the Object reference u. I doubt my proposed method will work. Do you have a better idea? -
Convertion string to Calender object
The input string format is "hh-mm-ss". How can I convert to Calender object.
Can anybody suggest ?
Thanks
PravatUse a java.text.SimpleDateFormat to convert the string to a java.util.Date object and then set the calendar object from that.
-
Object of class stdClass could not be converted to string
Dear all,
Im very new in PHP development and trying to consume a ASP.NET webservice.
This is my code:
<HTML>
<HEAD>
<TITLE>New Document</TITLE>
</HEAD>
<BODY>
<?php
require_once('lib/nusoap.php');
$soap = new SoapClient('https://testsoap.test.nl:446/Service1.asmx?wsdl');
try {
$result = $soap->testPhp();
echo "$result";
} catch (SoapFault $e) {
echo "Error: {$e->faultstring}";
?>
</BODY></HTML>
When running this, im getting this error:
PHP Catchable fatal error: Object of class stdClass could not be converted to string . on line 14.
And this is line 14 in my code:
echo "$result";
Can anyone help me with this issue?
ThanksWithout knowing what version of PHP you are using and also there does not seem to be an SAP angle, have you tried var_dump() instead of echo.
e.g. var_dump($result);
http://php.net/manual/en/function.var-dump.php -
Converting String to Calendar Object
Hi,
I nedd to Change the below String to Calendar Object.i want to show the records which are older than half an hour.any other idea which will solve my problems?
Fri Aug 17 01:56:40 GMT+05:30 1906
Thanks in advance.
Regards:
Akash.Look at
java.text.SimpleDataFormat -
How do I know if I can convert a String value to an int value or not?
Hi,
I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
Thank youEncephalopathic wrote
Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
Write a class definition of a class named 'Value' with the following:
a constructor accepting a single integer paramter
a constructor with no parameters
a method 'setVal' that accepts a single parameter,
a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
The setVal(int y) returns nothing, so how do I know whether it has been called or not?
Thank you
Maybe you are looking for
-
Error while transporting a WEBservice Datasource
Hi all, I am trying to transport a web service datasource(PI data to BW) in testing system . But while transporting ,I get the following error in the logs of my transport request. Error generating the Web service /BIC/CQZPI_KPI00002000 This is not
-
I have a MacBook Pro bought in dec 2009. Currently has mountain lion osx installed. Worked like a dream until today. Randomly froze, so I restarted it. To find I got a grey screen. It wouldn't start. Also note my DVD drive doesn't work, but mountain
-
Attaching a PDF document for a Invioce Parking thru FB60 in background
Dear Friends, I am working on a requirement to build an interface for Invoice posting/Parking. Transaction used: FB60 Invoice data will be stored in a staging server, same has to be read and posted in SAP. Till posting part i am clear with the requir
-
Run batch files through java code
Hi All I need to run a batch file using java code . I am not getting any error, but also no output. Can someone let me know the problem with my code.The code i am using is import java.io.*; public class batchtest { public static void main(String
-
Editing video in Photoshop - apply to all frame
I'm editing some HD video in Photoshop. I have a filter (Gaussian blur in an area selection) that I want to apply to all frames of the video. I can do it by selecting each layer at a time (it works, but painfully slow) but how do I apply the same fi