how to convert a String to Object in JAVA - java

I am retrieving a String variable from the Database and storing in a variable.
String name = "Peter" ---- >(retrieved from the database)
I already have a class called Peter. I need to initialize the class using the retrieved variable name.
Assume that ,whatever String is retrieved from the database , I have a class defined for it in my package...
Is there a way to create a Object for the String I retrieve from the Database?

Class.forName(name).newInstance()

Using Class.forName() - java.lang.reflect
If we know the name of the class & if it has a public default constructor we can create an object in this way.
Class myClass = Class.forName("MyClass");
Class[] types = {Double.TYPE, this.getClass()};
Constructor constructor = myClass.getConstructor(types);
Object[] parameters = {new Double(0), this};
Object instanceOfMyClass = constructor.newInstance(parameters);
See Java how to instantiate a class from string

Related

How to use setter for this Kotlin class property?

I have the following class coded in Kotlin:
class MyClass {
var color: String = ""
var action: String = ""
val owners = Array(1) {Owner()}
class Owner {
var userId: String = ""
var userName: String = ""
}
}
...and I'm accessing it Java:
MyClass myObject = new MyClass();
myObject.setColor("blue");
myObject.setAction("throw");
...and I'd like to be able to set the owner. I'm not sure how, though. If it were an object that was coded in Java with public members, I'd just do something like:
myObject.owners[0].userId = "001";
myObject.owners[0].userName = "Freddy"
Since the object was coded in Kotlin, I need to user a setter in Java.
How do I set the properties in the first element of an array with a setter?
For each Kotlin property foo, you can call its getter in Java as getFoo() and, if the property is mutable, the setter as setFoo(value).
See: Calling Kotlin from Java — Properties
In your case, just access the array with the getter, take its item and call the setters: myObject.getOwners()[0].setUserId("001"); and myObject.getOwners()[0].setUserName("Freddy");, or assign the Owner to a local variable:
MyClass.Owner owner = myObject.getOwners()[0];
owner.setUserId("001");
owner.setUserName("Freddy");
Use getOwners which will return owners object then set the value.
myObject.getOwners()[0].setUserId("001");
myObject.getOwners()[0].setUserName("Freddy");

forName returned value as Type

Can I use Class value returned by Class.forName as a type ?
e.g.
String hdrClassName = "generated.MessageHeader";
Class msgHdrClass= Class.forName(hdrClassName);
JAXBElement<msgHdrClass> jaxbWrapperElement1 = (JAXBElement<msgHadrClass>)jaxbUnmarshaller.unmarshal(new File("./src/MessageHeader.xml"));
If not, Is there a way to achieve "using class name passed at run time as type in java"?

How to get original class of a field declared in java class

Here we go, suppose if i have class Name :
class Name {
String firstName, lastName;
// getters and setters, etc.
}
and then Name class's object is declared somewhere in other class :
class Other {
Name name;
// getter and setters, etc.
}
Now if i do something like :
Other o = new Other();
Field[] fields = o.getClass().getDeclaredFields();
fields[0] --> is 'name' the Object of 'Name' class
but when i say field[0].getClass() :
It gives me java.lang.reflect.Field class object and not Name class object.
How can i get original class object from a field like 'name'
Field.getType method returns a Class object that identifies the declared type for the field represented by this Field object.
This should help
Other o = new Other();
Class<?> classTemp1 = o.getClass();
Field[] allFields = classTemp1.getDeclaredFields();
Now u can query each field for name ,type etc
fields[i].getType()
Please check
http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#getType()
getType() Returns a Type object that represents the declared type for the field represented by this Field object.
field[0].getClass()
Will return you the Type object that represents field[0] which is obiviously field[0].
Basically, you need to ask the field for the value of a specific instance, something like
Name name = (Name)fields[0].get(o);
Now. It's pretty dangrous to do a blind cast like this, I'd be probably simply assign it to a Object first and then do instanceof or maybe use Field#getName to determine the name of the field and take action from there...
nb- I'd make mention of getType, but Evgeniy Dorofeev beat me to it and I don't want take away from his answer
Based on Evgeniy's answer, this line is what you are looking for:
String actualClassName = fields[0].getType().getName();

Java - Reflection. Set value for the class object which are dynamically created

Hi have a class[many] for which I create object dynamically during run time. now I want to set value for the fields which are private fields. How do I set them.
I have seen many examples which explain this but we need to know the field name and only than the values can be set.
for my case I have some set of default values for set of primitive and non primitive types and find the field type during run time and set the default values for them.
For example:
LoginBean loginBean = new LoginBean();
Method setUserName = loginBean.getClass().getMethod("setUserName", new Class[]{String.class});
setUserName.invoke(loginBean, "myLogin");
My case is different and i don't even know the field name but have to set the default value according to field type.
how to do this using reflection or even better in spring.
You can say yourBean.class.getFields(); which will give array of Field.
Using Field you can find its name and type, and do the desired work (setting some value, if its type is == some primitive type)
This example sets default values on several fields within a class using reflection. The fields have private access, which is toggled on and off via reflection. Field.set() is used to set the values of the field on a particular instance instead of using the setter method.
import java.lang.reflect.Field;
import java.util.Date;
public class StackExample {
private Integer field1 = 3;
private String field2 = "Something";
private Date field3;
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
StackExample se = new StackExample();
Field[] fields = se.getClass().getDeclaredFields();
for(Field f:fields){
if(!f.isAccessible()){
f.setAccessible(true);
Class<?> type = f.getType();
if(type.equals(Integer.class)){
f.set(se, 100); //Set Default value
}else if(type.equals(String.class)){
f.set(se, "Default");
}else if (type.equals(Date.class)){
f.set(se, new Date());
}
f.setAccessible(false);
}
System.out.println(f.get(se)); //print fields with reflection
}
}
}
1) By Using Spring Constructor/Setter Injection. You dont need to know the attribute name , just type will do. Like as following:
<bean id="myBean" class="myBean">
<constructor-arg type="int"><value>1</value></constructor-arg>
</bean>

How to invoke a string from a class using method.invoke(-,-)

Here i am trying to get uContainer object from another project. uContainer having all the setters and getters with return values set from properties file. Like a user properties for perticular user. I am using to get perticular method values from uContainer instance. But in the 4th line my application getting crashed.
uContainer is an instance of UserContainer class.
getSingleResultListing also a boolean variable in UserContainer class having with getters and setters methods.
The code is given below.
Method getUContainer = form.getClass().getMethod("getUserContainer", new Class[0]);
Object uContainerObj = (Object)getUContainer.invoke(form, new Object[0]);
Method getFlagValueMethod = uContainerObj.getClass().getMethod("getSingleResultListing", new Class[0]);
String flagValue = (String)getFlagValueMethod.invoke(uContainerObj, new Object[0]);
log.info(">>>flagValue: "+flagValue);
boolean singleListingFlag = Boolean.getBoolean(flagValue);
log.info(">>>singleListingFlag: "+singleListingFlag);
here in the fourth line while invoking the uContainer object i am getting error ..
Thanks..
You are casting the returned object to a String, but you are not getting a String from that method. You cannot convert objects to String via a cast operator. If you want the string representation, write
String flagValue = getFlagValueMethod.invoke(uContainerObj, new Object[0]).toString();

Categories

Resources