I am reading string xml data from other application in my project using JAXB.
They have provided their appdata.jar. (I dont have control on their classes).
They have MessgeBody. In MessageBody they have defined one private instance variable without getter and setter. And because of this I am not able to obtain instance of perticular class.Remaining fields with getter n setter are accessible.
I tried Java reflection , it is not working.
Here is my code -
Class Test{
public void parseXMLStr(){
String xmlStr="<xml><first></first><second></second><third></third></xml>"
//I am able to get values of first and second as getter and setter defined.
First f =getMessageBody().getFirst();
f.dosomething().. //working
Second s =getMessageBody().getSecond();
s.dosomething()...//working
}
appdata.jar(other application) contains MessageBody as,
class MessageBody{
private First first;//getter setter provided
private Second second;//getter setter provided
private Third third;//getter setter NOT Provided
}
How I can obtain Third class instance and access variables inside it.
I tried Java reflection as below but I am getting null pointer exception(although data is there )
Field f = obj.getClass().getDeclaredField("third");
f.setAccessible(true);
Third t = (Third) f.get(obj);
t.getName();//here getting nullpointer exception
Related
I have 2 objects which are related
One of them is of class Attribute, the other one is something like controller of that called AddAttributeActionHandler
The Attribute object has a lot of fields in it which I need to set in AddAttributeActionHandler Both classes have getters and setters some of them are equal.
Basically what I what is to copy every available getter from the class Attribute and invoke according setter method on the class AddAttributeActionHandler
In other words I can execute the following (you can call it "manual" setting)
Attribute attributeObj = getAttributeObj();
String codeFromAttrObj = attributeObj.getCode();
String titleFromAttrObj = attributeObj.getTitle();
AddAttributeAction action = AddAttributeAction.create();
action.setCode(codeFromAttrObj);
action.setTitle(titleFromAttrObj);
The problem is that there are just like 50+ fields. I'd like it to be fully automatic.
So, I've found the following code for getting every available public getter for the object Attribute
for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(attributeObj.getClass()).getPropertyDescriptors())
{
if(propertyDescriptor.getReadMethod().toString() != "null")
{
String getterMethodName = propertyDescriptor.getReadMethod().toString();
String getterMethodValue = propertyDescriptor.getReadMethod().invoke(attributeObj).toString());
}
}
The code above gets every getter available in the object and prints its value.
Now I need to find out whether there's a corresponding setter method in the object of the class AddAttributeActionHandler and set the property which I got from the getter in the Attribute object.
Is it possible?
If so, please provide any clues.
Thanks in advance!
I am creating a new library in which I have a class(UserResponse) with 6 String variables, we have set of 3 constructors with parameters using which we are currently creating objects.The first version of lib is successfully running, for the 2nd version of lib I am asked to remove all the constructors of UserResponse class, but there are some classes which are using parameterized constructor to create objects. I cannot create object using default cons and use setter to set values. Is there any better way to create object with parameters initialized.
public class UserResponse{
private String s1;
private String s2;
private String s3;
private String s4;
private String s5;
private String s6;
//getters and setters
//Parameterized Constructors
}
class SomeService{
public UserResponse someMethod(){
//business logic
return new UserResponse(value1, value2, value3);
}
}
It depends on your class utilization manner it has been designed for.
If the class' clients must have the ability to construct the response freely, with arbitrary fields set - builder pattern would serve the need. This approach is used, for example, in Atlassian Confluence Model API, look at Content's builder() method. You cannot construct Content directly (all constructors are private) or mutate it (no setters), so you build it like this:
Content.builder()
.space(currentSpace)
.parent(parentPage)
.title(titleToUse)
.type(ContentType.PAGE)
.body(bodyToUse, ContentRepresentation.STORAGE)
.build()
Builder is internal and have access to all fields.
If there are a limited amount of use cases for the class construction, then factory-based idea fits better:
Content::Factory::buildResponseForUseCase1(/* use case specific parameters set*/)
Content::Factory::buildResponseForUseCase2(/* list of parameters dictated by use case 2 */)
Does ReflectionTestUtils works only on fields of a class, not on variables defined inside a method of that class?
I tried to test the fields of a class, it works perfectly fine using ReflectionTestUtils, if I try it on variables of a method, I get an IllegalArgumentException.
Example Code:
public class Check {
String city;
public void method() {
city = "Bangalore";
String Street = "MGRoad";
}
}
If I want to have a JUnit tests for the above class using ReflectionTestUtils.
Check c = new Check();
assert ReflectionTestUtils.getField(c, "city").equals("Bangalore")
-> works fine.
assert ReflectionTestUtils.getField(c, "Street").equals("MGRoad")
-> gives illegalArgumentException.
Please have a look and suggest me if I can test the attributes of a method.
You cannot access local variables using reflection and String Street = "MGRoad"; is local variable to that method
If what you mean is variables local to methods/constructors, you can not access them with reflection. ... There is no way to obtain this information via reflection. Reflection works on method level, while local variables are on code block level.
I'm using IReport (JasperStudio plugin for Eclipse) and I'm trying to create a report with a JavaBean as source.
Suppose I have these two classes:
public class MyClass {
private String myClassAttribute;
// getter and setter for myClassAttribute
}
public class AnotherMyClass {
private String anotherMyClassAttribute;
private MyClass myClass;
// getter and setter for anotherMyClassAttribute
// getter and setter for myClass
}
If I choose AnotherMyClass as JavaBeanSource I can set only fields from that class (anotherMyClassAttribute), I didn't find a way to set a text to getMyClass().getmyClassAttribute().
Do JavaBeans stop at level one or is there a way to use attribute from other classes between references?
Thanks.
In report define field $F{myClass} with type MyClass
In text field use expression $F{myClass}.getMyClassAttribute()
No, it doesn't stop at level one, you may go as deep as you want. You may use the attribute like myClass.myClassAttribute. And for setting a value to it, myClass.myClassAttribute = "some value"
I'm trying to create an object (LineItem), and then create variables of that object. I want to create a 'cookie' that has a price, a name, and a quantity assigned to it. My problem begins at cookie.price = 5, my IDE tells me that 'package cookie does not exist.' I am very confused. It gives me the same error whether or not I declare cookie outside of the LineItem class.
public static void main(){
public class LineItem{
int price;
String foodName;
int quantity;
LineItem cookie = new LineItem();
cookie.price = 5;
}
}
In Java, you cannot directly write the executable statements in class.Only variables declaration is allowed outside the method/blocks/constructor
You need to move the code cookie.price = 5; into a method/constructor/block.
Put it into a method. You have not got a main method and your program cant start this way. No research done. Use proper syntax and learn the basics. To refer to the class use the this keyword. You shall not create an instance of the class again in the same class. Instead of using this.variable you can refer to the variable straightforward if it is in the same class declared outside of any methods