Let, say for instance i have a POJO class employee with three attributes
1.Name (String)
2.Location (String)
3.Date of Birth (Date)
then i fired a query into database which retrieve first row of table and populate this POJO
with table data as follows:-
Name - john
location - USA
Date of Birth - 27/09/2014
To retrieve the values from this POJO i have to call getName(),getLocation() and getDOB().
But is there any method by which i can get all the values which is store in the POJO, in an Object type array without using getter method
for example:
Object[0] has the value "John".
Object[1] has the value "USA".
Object[2] has the value "27/09/2014".
(In my case, there are around 80 attributes in a class and number of these attributes increases because of client requirements and i am fetching each and every value by getter method and every time a single attribute is added i have to write a getter method in the code to fetch values. I basically want a more dynamic solution to this problem.)
you can try this:
String[] getObjectsPublicMethods(Object o)
{
Class clazz = o.getClass();
Method[] methods = clazz.getDeclaredMethods();
String[] result = new String[methods.length];
for (int i=0; i<methods.length; ++i)
{
try
{
result[i] = (String) methods[i].invoke(o, new Object[] {})
} catch (IllegalAccessException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e)
{
}
}
return result;
}
This method uses reflection to get the information you want, BUT
it assumes that the getter methods are declared public in this class AND
that all of the public methods return String.
I think what you are looking for is called reflection.
i hope this link helps http://docs.oracle.com/javase/tutorial/reflect/index.html
or this answer:
Is it possible to use Java Reflection to print out attributes of the parent class?
Related
I have a model entity which has a LIST type field, which stores the value in the form a string (comma separated) in sql.
I am trying to implement a custom converter which would return all the samples which has a particular list element.
If the values are "A,B,C","A","B,C",. If I provide "A", I want to retrieve both the samples containing both "A,B,C" as well as "A".
This custom converter just returns the sample which has value "A".
RSQLJPASupport.addConverter(List.class, s -> {
try {
return Arrays.asList(s.split(","));
}catch (final IllegalArgumentException ex){
return null;
}
});
Please help! I followed these steps btw: https://github.com/perplexhub/rsql-jpa-specification
Assume the name of the field codes, you could use
repository.findAll(toSpecification("codes=='A' or codes=='A,' or codes==',A' or codes==',A,'"))
I have an implementation where when user click on checkbox , a json gets associated as value of checkbox and that value is passed to my bean class.
And In the method invoked, the String is then parsed into JSON object.
When I select two checkbox, it works perfectly fine. But if I select one checkbox, then it gives me error.
Here is my Checkbox Bean class -
private ArrayList<String> Ancillary=new ArrayList<String>() ;
public ArrayList<String> getAncillary() {
for(int i=0;i<Ancillary.size();i++){
System.out.println(i+"Object:" +Ancillary.get(i)+"\n\n\n");
}
return Ancillary;
}
public void setAncillary(ArrayList<String> ancillary) {
Ancillary = ancillary;
}
Here is my method where I print value of a Particular key in JSON.
public Event updatePax(RequestContext context) throws Exception {
ExtrasMenu extrasMenu = (ExtrasMenu) context.getConversationScope().get(ScopeKeys.EXTRASMENU);
System.out.println("As a string:"+extrasMenu.getAncillary().toString());
JSONObject json=new JSONObject(extrasMenu.getAncillary().get(0));
System.out.println(json.get("firstName"));
}
And here is the Output-
If only one checkbox is selected -
0Object:{"firstName":"TIMOTHY"
1Object:"lastName":"WALKER"
2Object:"price":100}
If two or more checkboxes are selected -
0Object:{"firstName":"TIMOTHY","lastname":"WALKER","price":"50"}
1Object:{"firstName":"ANNE","lastname":"WALKER","price":"150"}
Since, I couldnt figure out why ArrayList is taking input like this,
I created a special case when User selects one check box. I will take the ArrayList and convert it to a String using toString.
So, the output of toString will be like -
{"firstName":"TIMOTHY","lastname":"WALKER","price":"50"}
Now I used a try catch block to create JSON object out of the string I get from toString.
JSONObject json=null;
try{
json=new JSONObject(extrasMenu.getAncillary().get(i));
}
catch(org.json.JSONException e){
int len=extrasMenu.getAncillary().toString().length();
json=new JSONObject(extrasMenu.getAncillary().toString());
}
So If it throws an error, the full list as a string will be used to create JSON object.
Although It is working fine, Still I am not very sure about Why ArrayList is working like this !
i am very new to JAVA 8 and SPRING MVC . I have a java bean which is a POJO with setter and getter. My Spring web service using reflection maps the request parameters to the POJO.
I want to do input validation using annotation. I have a requirement were i need to read all the values of the annotated field and check atleast one value is provided. I wrote a sample code.... BUT NOT SURE HOW TO GET THE VALUES THAT ARE ASSIGNED TO A FIELD. Please do share sample code if you have:
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
boolean canProceed = false;
for(Field field : DocumentSearchRequest_global.class.getDeclaredFields())
{
if (field.isAnnotationPresent(ValidDocumentModifiedDate.class))
{
String name = field.getName();
//IAM ABLE TO GET THE NAME OF THE FIELD
System.out.println("1.name : "+ name);
System.out.println("2. "+field.getType().getName());
}
}
// Method[] method = DocumentSearchRequest_global.class.getDeclaredMethods();
for (Method method :DocumentSearchRequest_global.class.getDeclaredMethods() )
{
System.out.println(method.getName() );
//ABLE TO GET NAME OF THE GETTER AND SETTER METHODS IN THE POJO
//CAN U SUGGEST HOW TO READ THE VALUE OF A PARTICULAR FIELD.. EITHER BY //GETTING THE VALUE FROM THE GET METHOD??? ...
}
You can get the values by calling method.invoke(Object, Object...) where first parameter is your class instance on which method is to be executed and second variable arguments are arguments of the method. In your case it'll be null or empty. Here is simple code snippet Object value = method.invoke(DocumentSearchRequest_global_instance);
My class has multiple fields with getter and setter
While trying to access the value of a property of a bean i have to check the property name and retrieve the value..
if(property is this )
mybean.getThisProperty()
else if(property is that )
mybean.getThatProperty()
else...
How i can retireve without actually checking for the propertyname ..
BeanUtils.copyProperties in Spring copies property from one bean to another
I'm not sure what you are trying to accomplish, but you can do something like that using Reflection:
for (Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value;
try {
if (name.equals(desiredPropertyName)) {
value = field.get(object); // Do whatever you want with the
// value
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
In the above code, we are getting all properties in the "object" eve the private fields without using the getter.
This line gives us access to the private fields:
field.setAccessible(true);
This line retrieves the name:
String name = field.getName();
This line retrieves the value:
value = field.get(object);
If you really want to use the getter, then that's another subject, where you will have to use reflection to invoke methods.
How about the
PropertyUtils.getSimpleProperty
of Apaches commons.beanutils
java.lang.NoSuchFieldException: id
The below line is creating the exception.
String fieldValue =String.valueOf(studyplanCategory.getClass().getField(filterProperty).get(studyplanCategory));
studyplanCategory is a valid object and has got actual values. Beacuse of this exception the load method and the search function in the LazyLoading DataTable of my JSF webapp is not working.
From the Javadoc for Class.getField(...):
Returns a Field object that reflects the specified public member field
of the class or interface represented by this Class object. The name
parameter is a String specifying the simple name of the desired field.
The field to be reflected is determined by the algorithm that follows.
Let C be the class represented by this object:
If C declares a public field with the name specified, that is the
field to be reflected. If no field was found in step 1 above, this
algorithm is applied recursively to each direct superinterface of C.
The direct superinterfaces are searched in the order they were
declared. If no field was found in steps 1 and 2 above, and C has a
superclass S, then this algorithm is invoked recursively upon S. If C
has no superclass, then a NoSuchFieldException is thrown. See The Java
Language Specification, sections 8.2 and 8.3.
If the field you are trying to retrieve via:
studyplanCategory.getClass().getField(filterProperty)
is private, then you will get a NoSuchFieldException. For private fields, try this instead:
studyplanCategory.getClass().getDeclaredField(filterProperty)
And to get around potential illegal access exceptions when setting values via a field this way:
Field field = studyplanCategory.getClass().getDeclaredField(filterProperty);
field.setAccessible(true);
field.get(studyplanCategory);
App fires up this exception because its doesn't see attribudes your want to give back.
Method getField() return non-private attribudes so if your attribudes are private, method doesn't see them. You can check http://docs.oracle.com/javase/tutorial/reflect/member/fieldTrouble.html
So you can do that your attribudes will change on protected or public and then should work it right. But this way (its same like example on primefaces) simulate real database.
public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
List<Car> data = new ArrayList<Car>();
//filter
for(Car car : datasource) {
boolean match = true;
for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
String filterValue = filters.get(filterProperty);
String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));
...
So this list simulate real database only for example. If you want to use it. so you shoud do it on backing bean class and there do it. You open connection already with some filter or don't and then return data from database.
//EDIT: Man wrote that you should use getDeclaredField() but i did try this and it didn't work well, and throws up IlegalAccessException. When a pretype attribudes to protected, it works fine. I don't know why.
Best solutions for getClass().getField() problem are:
Use getDeclaredField() instead of getField()
1)
String propertyName = "test";<br/>
Class.forName(this.getClass().getName()).getDeclaredField(propertyName);
2)
String propertyName = "name";<br/>
Replace **"HelloWorld"** with your class name<br/>
HelloWorld.class.getDeclaredField(propertyName)
I had faced the same problem. My issue was my variables are not public . Make sure your class variables are public
private Object getVariableValue(Object clazz, String variableName) {
try {
Field field = clazz.getClass().getField(variableName);
return field.get(clazz);
} catch (NoSuchFieldException e) {
return "";
} catch (IllegalAccessException e) {
return "";
}
}
I agree that we should Use getDeclaredField() instead of getField()
private Field getOwnProperty(Object clazz, String propertyName) {
try {
return clazz.getClass().getDeclaredField(propertyName);
} catch (NoSuchFieldException e) {
log.warn( "Object has no property : " + propertyName );
return null;
}
}