Java string to object instance

Convert String into a Class Object [closed]

It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object. How to do that? Please help me with source code.

9 Answers 9

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is . well . a serious misconception on your part.

SomeClass object = . String s = object.toString(); 

then the answer is that there is no simple way to turn s back into an instance of SomeClass . You couldn’t do it even if the toString() method gave you one of those funky «SomeClass@xxxxxxxx» strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object’s identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.

If you did something like this:

SomeClass object = . Class c = object.getClass(); String cn = c.toString(); 

then you could get the same Class object back (i.e. the one that is in c ) as follows:

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)

If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn’t be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant’s answer.
  • JSON serialization as described in @fatnjazzy’s answer.
  • An XML serialization library like XStream.
  • An ORM mapping.
Читайте также:  Css margins border box

Each of these approaches has advantages and disadvantages . which I won’t go into here.

Источник

Create new object from a string in Java

Also, if possible does the resulting object have to be of type Object? There may be a better way, but I want to be able to retrieve values from an XML file, then instantiate the classes named after those strings. Each of these classes implement the same interface and are derived from the same parent class, so I would then be able to call a particular method in that class.

6 Answers 6

This is what you want to do:

String className = "Class1"; Object xyz = Class.forName(className).newInstance(); 

Note that the newInstance method does not allow a parametrized constructor to be used. (See Class.newInstance documentation)

If you do need to use a parametrized constructor, this is what you need to do:

import java.lang.reflect.*; Param1Type param1; Param2Type param2; String className = "Class1"; Class cl = Class.forName(className); Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class); Object xyz = con.newInstance(param1, param2); 

I think that using getConstuctor is better than using the init method. As using a constructor allows for final fields to be assigned.

You should also be aware if you use: Object xyz = Class.forName(className).newInstance(); you will silently convert checked exceptions to unchecked exceptions. More details in this answer: stackoverflow.com/a/7495850/411401

Yes, you can load a class on your classpath given the String name using reflection, using Class.forName(name), grabbing the constructor and invoking it. I’ll do you an example.

com.crossedstreams.thingy.Foo 

Which has a constructor with signature:

I would instantiate the class based on these two facts as follows:

// Load the Class. Must use fully qualified name here! Class clazz = Class.forName("com.crossedstreams.thingy.Foo"); // I need an array as follows to describe the signature Class[] parameters = new Class[] ; // Now I can get a reference to the right constructor Constructor constructor = clazz.getConstructor(parameters); // And I can use that Constructor to instantiate the class Object o = constructor.newInstance(new Object[] ); // To prove it's really there. System.out.println(o); 
com.crossedstreams.thingy.Foo@20cf2c80 

There’s plenty of resources out there which go into more detail about this, and you should be aware that you’re introducing a dependency that the compiler can’t check for you — if you misspell the class name or anything, it will fail at runtime. Also, there’s quite a few different types of Exception that might be throws during this process. It’s a very powerful technique though.

Источник

How do I create Java built-in object from string

I was able to create MyObject. My question is how can I create a Java built-in object such as Long or String from string. I need to do this because I can only know the type of object in run time in text format. I did this but didn’t work.

Object obj = Class.forName("java.lang.Long").newInstance(); 

As an aside: even though it’s obvious to most people who can answer this question why your second code sample didn’t work, you should avoid only saying «this didn’t work» on SO. Give us the stack trace and error message. And preferrably look at the error message and see if it helps you resolve the error.

Читайте также:  Configure php on iis server

2 Answers 2

java.lang.Long does not have a no argument constructor, so you can’t call newInstance like that. Instead, you have to look up the constructor with the correct arguments, build the argument array, and then invoke the Constructor.

Constructor constr = Class.forName("java.lang.Long").getConstructor(String.class); Object myLong = constr.invoke("5"); 

Read the documentation for newInstance() , it will tell you that it calls the no-parameter constructor of a class. If the built-in (or any other) class has such a constructor, you can create it just the same. Otherwise, you’ll have to call the specific constructor by using Class.getConstructor() , and pass it the appropriate parameters. So, to call the new Long(String) constructor for example:

Class.forName("java.lang.Long") .getConstructor(String.class) .newInstance("12345"); 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to parse a String variable into any data type in Java?

I want to build a method that can convert a String value to a given Field object data type through Java Reflection. Here is my code:

String value = . ; Class clazz = getClazz(); Field f = clazz.getDeclaredField("fieldName"); boolean fieldIsAccessible = f.isAccessible(); if (!fieldIsAccessible) < f.setAccessible(true); >f.getType().cast(value); if (!fieldIsAccessible)

When I run this code at firs attempt, I receive this exception java.lang.ClassCastException . I want to convert value to class java.math.BigDecimal . What is my code missing ? EDIT: View the solution I came up with.

Can’t understand what you are really trying to do. Why are you casting String type to the type of Field that you are not sure what it can be?

@ppeterka.. Don’t know why but you would again have to delete that comment, because you again went a little bit rude. lol 🙂

@ppeterka Actually I’m trying to parse a String value into a java class selected from a closed list of java classes from the JDK. I’m building a generic tool.

10 Answers 10

You could make this work for classes that have a string constructor like this: f.getType().getConstructor( String.class ).newInstance( value );

+1 Yep, and for your own classes you can provide a static method valueOf(String) as a factory method. You then check (via reflection, or you could use a marker interface) if that method is present in the field’s type and use it to create the instance.

Читайте также:  Python найти элемент последовательности

@Axel It appears from a later comment that the classes are «a closed list of java classes from the JDK» so adding static methods or marker interfaces are not possible. Reviewing them for String constructors and providing special case code for any that lack one might be feasible.

Oh, I hadn’t seen that. However even in that case the valueOf-approach has some kind of use — it works with enums and AFAIK also with all wrapper types.

In Java, there is no universal method for converting a String into an instance of an arbitrary class. Many classes simply don’t support such a conversion. And there’s no standard interface for those that do support it.

Your best bet is to look for a constructor that accepts a String as its sole argument. Of course, not every class provides such a constructor, and there’s no guarantee that the semantics would be what you’d expect.

There is a Github project (MIT Licensed) called type-parser which does converting a string value to the desired data type

Here is the project description from GitHub

This is a light weight library that does nothing but parse a string to a given type. Supports all applicable java classes, such as Integer, File, Enum, Float etc., including generic Collection types/interfaces such as List, Set, Map, arrays and even custom made types. Also possible to register your own parsers.

As maerics said, you cant just cast a String to a data type. Is it possible you mean «how do I parse a BigDecimal from a String», to which the answer is.

fieldName = new BigDecimal(value); 

The Class cast method throws the ClassCastException if the object is not null and it not assignable to type T. There are only a few types of variable to which a String reference is assignable, String, Object, Serializable, Comparable, and CharSequence.

Many, but not all, classes have ways of producing an object instance based on a String. In some cases, including BigDecimal, there is a constructor that takes a String representation of the new object’s value. You could use the Class getDeclaredConstructor method specifying a single String argument, to get the Constructor object for such a constructor, if there is one. However, there is some risk that you will not get a useful object without e.g. calling some setXXX methods, and this approach is limited to those classes that have the right form of constructor.

You are presumably trying to solve some higher level problem, possibly related to serialization and deserialization. That problem may be much more easily solvable than your current problem.

Источник

Оцените статью