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);
}
Related
I am serializing a POJO using jackosn, and I want that all the values for which the user sets some value irrespective whether it's null or not must be included in the serialization.
So currently:
POJO:
public class YourItem {
public String key;
public String item;
}
Currently when user does:
YourItem item = new YourItem();
item.setKey("abc");
The serialization gives:
{
"key" : "abc"
}
as I configured ObjectMapper as objectMapper.setInclude(Include.NON_NULL)
However now if the user specifically calls the setter and sets the value as null, then I want that item in my serialized string.
So if user does
YourItem item = new YourItem();
item.setKey("abc");
item.setItem(null);
I want in serialzation both key and item values are present like:
{
"key" : "abc",
"item" : null
}
How do I differentiate between the user set null and the default null.
Is there a configuration in ObjectMapper ??
Some people consider using null to be bad practice (The book Clean Code, for instance)
Disregarding that, you cannot differentiate between the default initialization null and a user-set null by language-design
You need some sort of state that tracks if a field has been accessed by a setter. If it hasn't been accessed by a setter and is null, ignore it.
One way to do this is Jackson Filters, which allows you to define various conditions for serializing a field during runtime (your condition being that your setter-access-state indicates that the field was set by a user)
http://www.baeldung.com/jackson-serialize-field-custom-criteria
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);
For the following class I want to access an object if the name equals to something, let's say "you". Otherwise I want to create it.
I want to check if an object exists that has the name as 'you' and then add entries to the ArrayList contInstances. If such an instance doesn't already exist I want to create it. Next time I might have to use the same object so that I can add some more entries to the ArrayList.
public class Values {
String name;
ArrayList<anotherClass> classInstances = new ArrayList<anotherClass>();
}
This happens to be in a loop. How can I do that?
Edit: I'll quote an example here:
if (an object exists that contains field 'name' == 'YOU'){
add entries to the array list directly using the available object
}
else {
create a new object and set the 'name' = 'YOU';
add entries to the array list;
}
It sounds kind of like you want to have a cache by name. Instead of an ArrayList, consider using a Map<String, AnotherClass> to keep track of Name->Object mappings.
You can then use this approach:
Map<String, AnotherClass> instances = new LinkedHashMap<String, AnotherClass>();
for (...) {
String name = getNextName();
AnotherClass instance = instances.get(name);
if (instance == null) {
instance = makeInstance(name);
instances.put(name, instance);
}
useInstance(name, instance);
}
After that loop is finished, if you still want a List<AnotherClass>, you can use return new ArrayList<AnotherClass>(instances.values());
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);
}
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);