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);
Related
I have an object with some fields and they have setters. I want to iterate through a map from a request and based on the key name with value null - unset the field by doing something like
field1.set[key](null)
instead of having the request be a list and doing
list.forEach() {
if (list.contains(key)) {
object.setKeyName(null);
}
}
Is this possible? It would be more dynamic vs having to add a new if statement each time a new field is added to the model. Disregard sanitization of the input.
You can do that using Reflection.
for (String fieldName : list) {
Class parameterType; //get the type
object.getClass().getDeclaredMethod("set" + fieldName, parameterType).invoke(object, null);
}
I have an entity that is populated directly from an Excel file so every property is of type String. I am then mapping from this property to an actual entity that has all of the correct data types set using parses with try catch. For example:
InputEntity:
public class ProductInput {
String name;
String color;
String price;
String date;
}
ActualEntity:
public class Product {
String name;
String color;
Double price;
Date date;
}
Prior to doing the actual mapping I would like to log any errors to the database using an Error class I created.
The ultimate goal would be to make sure each value coming from the InputEntity is not null or empty and is the correct type (able to be set in the Actual Entity without any error). I want to use reflection to loop through the fields of the Product class and find the matching field on the ProductInput class. Then checking its value with the correct parse function to make sure it will eventually be able to be set in the Product entity. If there is an error I am going to create an error record that includes the property name that failed and store it in the database saying which input field has a problem.
Is reflection the correct way to go about this? I want the function to be generic enough to handle any classes as the input and actual assuming the properties of the input entity will always be string and the property names will match.
I was thinking somewhere along the lines of:
public validateFields(Class<T> inputClass, Class<T> destinationClass) {
Field[] inputFields = inputClass.getDeclaredFields();
Field[] destinationFields = destinationClass.getDeclaredFields();
for (Field field: destinationFields) {
// Check for same field in inputClass
// If it exists confirm value of field is not null or empty
// Additionally confirm the value of field can be parsed to the type of the destinationField
// Create error entity with property name if there is a problem
}
}
I have a task where object properties need to be populated from data received via JSON web service. The property names are mapped to the JSON keys. I am using the following code in an attempt to populate the object but the app crashes when it hits this line:
while(looper.hasNext()){
String key = looper.next();
String val = json.get(key).toString();
user.getClass().getDeclaredField(key).set(user, val); // crash
}
The object is called user. I have verified that the key variable does match a property in the user object. Any ideas on how to fix this? THanks!
you should set your field accessible
Field field = user.getClass().getDeclaredField(key);
if (field != null) {
field.setAccessible(true);
field.set(user, val);
}
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>
It is possible to access a class attribute by its name using the following code:
MyClass.class.getDeclaredField("myAtt");
is it possible to create a function which do reverse? i.e. a function which convert an attribute to its name?
EDIT: I'm adding this edit to make this more clear:
consider the following class:
class MyClass {
Integer myAttribute;
}
I am looking for a function which accepts myAttribute (itself, or a reference to it. idk!) and returns "myAttribute" string.
Try java.lang.reflect.Field.getName();
You can use Field#getName method : -
Field[] fields = MyClass.class.getDeclaredFields();
for (Field field: fields) {
System.out.println(field.getName());
}
PS: - You should name your classes starting with uppercase letters.
UPDATE: - Ok, if you have your name of the attribute: - private String attrName;, you can get the corresponding field my using: -
Field field = MyClass.class.getDeclaredField("attrName");
// Then do this. Which is meaningless. But I don't know why you want to do this
// Your fieldName will contain "attrName" which you know already
String fieldName = field.getName();
But fetching the name from the above field doesn't make sense. I would be surprised if you were looking for this only. But you can be more clear with your question.
If I understand your question you want to get the name of the Field thats current value matches the value of a variable.
private String getAttributeName(Object myInstance, Object myValue) throws IllegalAccessException
{
Field[] fields = MyClass.class.getDeclaredFields();
for (Field each : fields)
{
if (each.get(myInstance).equals(myValue))
return each.getName();
}
return null;
}
Then you can call it,
getAttributeName(myInstance, myValue);