Abhisek
Abhisek

Reputation: 715

How to convert string type variable to user defined class type variable

I have a text file , I am reading that text file and fetching some value from there, I am getting those value as string type. I have class that expects value of its type, this means I have to pass those strings which I am fetching from the text file by converting to my or better to say user defined class type. I am not able to convert the string to user defined class type. I am developing my code in core java. please suggest me how to convert this.

Upvotes: 0

Views: 4279

Answers (3)

Karel-Jan Misseghers
Karel-Jan Misseghers

Reputation: 807

so you have a string and want to make an object of it?

for example you read the string into input_String; can't you just give that string to the constructor of the class?

String input_String = textScanner.readLine() //or something like that
myObject = ClassToInstantiate(input_String);  

or am I not getting the question right?

Upvotes: 1

Swagatika
Swagatika

Reputation: 3436

Do you want something like this :

Class A {
   A(String str)
   {
      this.word = str;
   }
   private String word;
}

And then pass the objects of A, which will have the string values in the field.

Upvotes: 2

aioobe
aioobe

Reputation: 420951

Sounds like you're describing a form of parsing. You probably want to look into so called parser generators.

A parser translates text to objects (which seems to be what you need) and a parser generator takes as input a description of how to construct the objects from strings, and generates a parser accordingly.

A few examples I've used my self:

Upvotes: 1

Related Questions