Java self-reflection - java

It's rather strange, but I want to call self method.
This is my abstract class
public abstract class AbstractMapper {
public AbstractMapper(Map<String, String> map) {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field: fields) {
if (field.getAnnotation(Column.class) != null) {
String fName = field.getName();
String rsName = field.getAnnotation(Column.class).name();
StringBuilder sb = new StringBuilder("set")
.append(Character.toUpperCase(fName.charAt(0)))
.append(fName.substring(1));
String mName = sb.toString();
// this.invoke(mName, map.get(fName)); <-- What should I put this here?
}
}
}
public Result getCalculatedValues() {
return xxxx;
}
}
And this is my class
public class NewMachine extends AbstractMapper{
#column(name = machine)
private String machine;
#column(name = temperature)
private Double temperature;
// normal get/set methods
}
Now, my goal is that AbstractMapper constructor iterates through all fields with columns, and invoke all of its respective setters.
in this case, I can pass something like
Map<String, String> map = SomeClass.SomeMethod();
NewMachine m = new NewMachine(map);
Result r = m.getCalculatedValues();
Thank you for helping.

Try getClass().getMethod( mName, field.getType() ).invoke(this, map.get(fName) ) (and handle any possible exceptions ofc).
Additionally keep the JavaDoc on getDeclaredFields() in mind:
Returns an array of {#code Field} objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.
If you have a hierarchy you'd have to get the fields of the super classes as well.

Related

Copy fields and value of an object to a Map

I want to copy fields from a complex object- that is an object which contains other objects.
Now it copies wrapper classes with no issue but how do i copy the fields and values of the subclass
code
public Map<String, Object> getValueMapFromInsuranceVehicle(Long insuranceId) throws InvocationTargetException, IllegalAccessException {
InsurancePolicy insurance = repository.findById(insuranceId).get();
Method[] methods = insurance.getInsuranceVehicle().getClass().getMethods();
Map<String, Object> map = new HashMap<String, Object>();
for (Method m : methods) {
if (m.getName().startsWith("get")) {
Object value = m.invoke(insurance.getInsuranceVehicle());
map.put(m.getName().substring(3), value);
}
}
// add other fields specific to our needs like currentYear
return map;
}
From the code above it copies insuranceVehicle fields correctly, But i would like to copy the whole InsurancePolicy object and put the values in a map.
when i try it with InsurancePolicy i get exception cannot convert InsurancaCalculation into String,
my Insurance policy object looks like this
class InsurancePolicy {
#OneToOne
private Person person;
#OneToOne
private Vehicle vehicle;
#OneToOne
private InsurancePolicyStatus status;
private LocalDate policyStart = LocalDate.now().plusDays(1);
private LocalDate policyEnd = policyStart.plusYears(1).minusDays(1);
private boolean policy_AC = true;
private boolean policy_OC = true;
private boolean policy_ASS;
private boolean policy_NNW;
private String vehicleUsageType;
InsuranceCalculation calculation
#Embedded
private InsuranceVehicle insuranceVehicle;
#Embedded
private InsuranceCustomer customer;
private String coownerHowMany;
private String abroad;
}
Finally my question how can i improve my method getValueMapFromInsuranceVehicle() to get more fields copied ?
basically how to make this code below to work
public Map<String, Object> getValueMapFromInsuranceVehicle(Long insuranceId) throws InvocationTargetException, IllegalAccessException {
InsurancePolicy insurance = repository.findById(insuranceId).get();
Method[] methods = insurance.getClass().getMethods(); // insurance instead of vehicle
Map<String, Object> map = new HashMap<String, Object>();
for (Method m : methods) {
if (m.getName().startsWith("get")) {
Object value = m.invoke(insurance); // insurance instead of insurancevehicle
map.put(m.getName().substring(3), value);
}
}
// add other fields specific to our needs like currentYear
return map;
}
To get the methods of other objects in InsurancePolicy you could use your same code but add some checks for if the object is InsuranceCustomer, InsuranceVehicle, or InsuranceCalculation by using instanceOf and if it is use the same code just with Method[] methods = insurance.getClass().getMethods(); changed to the objects class. I would recommend separating your code into more methods so you can use recursion.

How to call class method by java annotation name with Jackson?

Wondering if there is a way to call the getter methods by the Jackson annotation property name (eg. "value") instead of the method name (eg. getName()) or point me to the right direction?
public class Person {
private String name;
#JsonProperty("value")
public String getName() {
return name;
}
#JsonProperty("value")
public void setSet(String name) {
this.name = name;
}
}
My goal is to call multiple methods by iterating trough a list of java annotation property names.
If you really want to identify and call the methods directly you could use reflection. Something like (with no exception management):
SomeObject object = ...;
Class<?> type = object.getClass();
for (Method method : type.getMethods()) {
JsonProperty property = method.getAnnotation(JsonProperty.class);
if (property != null && property.value().equals("value")) {
if (method.getParameterCount() == 0) {
Object value = method.invoke(object);
...
}
}
}
This is what I used as an answer by Allen D.
Map<String,Object> map = new ObjectMapper.convertValue(person, new TypeReference<Map<String,Object>>(){});
String s = (String) map.get("value");

How to use string to compare with field names in java?

I have a class named MyClass. It has many fields of type MyField. How do I return a reference to a particular field whose name matches a String's value?
public class MyClass{
public MyField field1;
public MyField field2;
public MyField field3;
public MyField whichField(String nameOfField){
//e.g. String = "field3", then return field3
//of course I can do if else, but it will be tedious If I have long list of MyField fields, can I iterate over all field names, and return whose name matches?
}
}
edit
I tried reflection from the answers below, I create a temp placeholder, and I wish to reutrn it but,
MyField temp = MyClass.class.getDeclaredField(whichFieldString);
doesnt work, I get type mismatch, cant convert error
How do I cast this?
How do I return this field?
As an alternative:
If all fields are of the same type and are accessed by their field name (most of the time) you could avoid the hassle and brittleness of using reflection by utilizing a Map.
The map associates a key (in your case the "field name") with a value. Instead of an arbitrary number of fields, MyClass would look like:
public class MyClass {
private final Map<String, MyField> fields = new HashMap<>();
/* code to initially fill the map */
public MyField whichField(String fieldName) {
return fields.get(fieldName);
}
}
You can do this with reflection. Class A has the fields we want to search through:
public class A {
private String field1;
private String field2;
private String field3;
}
And B shows how to iterate over the fields declared in A, matching on a particular field name:
public class B {
public B() {
Field field = findFieldByName("field1");
System.out.println(field);
}
private Field findFieldByName(String name) {
Field[] fields = A.class.getDeclaredFields();
for(Field f : fields) {
if(f.getName().equals(name)) {
return f;
}
}
return null;
}
public static void main(String[] args) {
new B();
}
}
You'll have to use reflection:
import java.lang.reflect.Field;
public class MyClass {
public MyField field1;
public MyField field2;
public MyField field3;
public MyField whichField(String nameOfField) {
MyField fieldName = null;
Field[] fields = MyClass.class.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(nameOfField)) {
// Do whatever you want to do
}
}
return null;
}
}
class MyField {
}
You may want to use a collection, e.g. Map<String, MyField>.
You can do it easily with reflection
Class<MyClass> clazz = MyClass.class;
Field requieredField = clazz.getDeclaredField("myFielldName");
EDIT
This solution is pertinent is the number of fields is fixed. As it was mentioned in comments and answers, if you want to store a dynamic number of values, then a Map (or a Collection if you only need to enumerate the values) is much more suitable.

class A declares multiple JSON fields

i have a class A which has some private fields and the same class extends another class B which also has some private fields which are in class A.
public class A extends B {
private BigDecimal netAmountTcy;
private BigDecimal netAmountPcy;
private BigDecimal priceTo;
private String segment;
private BigDecimal taxAmountTcy;
private BigDecimal taxAmountPcy;
private BigDecimal tradeFeesTcy;
private BigDecimal tradeFeesPcy;
// getter and setter for the above fields
}
and class B has got some private fiedls which are in class A
now when i try to create JSON string from above class A i get the following exception :
class com.hexgen.ro.request.A declares multiple JSON fields named netAmountPcy
How to fix this?
Since they are private fields there should not be any problem while creating json string i guess but i am not sure.
i create json string like the following :
Gson gson = new Gson();
tempJSON = gson.toJson(obj);
here obj is the object of class A
Since they are private fields there should not be any problem while creating json string
I don't think this statement is true, GSON looks up at the object's private fields when serializing, meaning all private fields of superclass are included, and when you have fields with same name it throws an error.
If there's any particular field you don't want to include you have to mark it with transient keyword, eg:
private transient BigDecimal tradeFeesPcy;
This is a bit late, but I ran into this exact same problem as well. The only thing was that I wasn't able to modify the superclass as that code wasn't mine. The way that I resolved this was by creating an exclusion strategy that skipped any field that had a field of the same name present in a superclass. Here is my code for that class:
public class SuperclassExclusionStrategy implements ExclusionStrategy
{
public boolean shouldSkipClass(Class<?> arg0)
{
return false;
}
public boolean shouldSkipField(FieldAttributes fieldAttributes)
{
String fieldName = fieldAttributes.getName();
Class<?> theClass = fieldAttributes.getDeclaringClass();
return isFieldInSuperclass(theClass, fieldName);
}
private boolean isFieldInSuperclass(Class<?> subclass, String fieldName)
{
Class<?> superclass = subclass.getSuperclass();
Field field;
while(superclass != null)
{
field = getField(superclass, fieldName);
if(field != null)
return true;
superclass = superclass.getSuperclass();
}
return false;
}
private Field getField(Class<?> theClass, String fieldName)
{
try
{
return theClass.getDeclaredField(fieldName);
}
catch(Exception e)
{
return null;
}
}
}
I then set the Serialization and Deserialization exclusion strategies in the builder as follows:
builder.addDeserializationExclusionStrategy(new SuperclassExclusionStrategy());
builder.addSerializationExclusionStrategy(new SuperclassExclusionStrategy());
Hopefully this helps someone!
The same error message also happens if you have different fields, but they have the same #SerializedName.
#SerializedName("date_created")
private Date DateCreated;
#SerializedName("date_created")
private Integer matchTime;
Doing copy/paste you can simply make such mistake. So, look into the the class and its ancestors and check for that.
You cannot have two fields with the same name.
You cannot have two fields with the same serialized name.
Types are irrelevant for these rules.
I used GsonBuilder and ExclusionStrategy to avoid the redundant fields as below, it is simple and straight forward.
Gson json = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes f) {
if(f.getName().equals("netAmountPcy")){
return true;
}
return false;
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}).create();
Add following lines at the bottom of proguard.config
(if you are using proguard in project)
-keepclassmembers class * {
private <fields>;
}
I don't think you should make the members transient, this might lead to errors because members that you might need in the future might be hidden.
How I solved this problem is to use a custom naming strategy and append the full class name to the Json, the downside of this is that it would lead to larger Json and if you need it for something like a Rest Api it would be weird for clients to name the fields that way, but I only needed to serialize to write to disk on android.
So here is an implementation of a custom naming strategy in Kotlin
import com.google.gson.FieldNamingStrategy
import java.lang.reflect.Field
class GsonFieldNamingStrategy : FieldNamingStrategy {
override fun translateName(field: Field?): String? {
return "${field?.declaringClass?.canonicalName}.${field?.name}"
}
}
So for all fields, the full canonical name would be appended, this would make the child class have a different name from the parent class, but when deserializing, the child class value would be used.
In kotlin adding the #Transient annotation for the variable on the parent class did the trick for me on a sealed class with open variables.
Solution for Kotlin, as suggested #Adrian-Lee, you have to tweak some Null Checks
class SuperclassExclusionStrategy : ExclusionStrategy {
override fun shouldSkipClass(clazz: Class<*>?): Boolean {
return false
}
override fun shouldSkipField(f: FieldAttributes?): Boolean {
val fieldName = f?.name
val theClass = f?.declaringClass
return isFieldInSuperclass(theClass, fieldName)
}
private fun isFieldInSuperclass(subclass: Class<*>?, fieldName: String?): Boolean {
var superclass: Class<*>? = subclass?.superclass
var field: Field?
while (superclass != null) {
field = getField(superclass, fieldName)
if (field != null)
return true
superclass = superclass.superclass
}
return false
}
private fun getField(theClass: Class<*>, fieldName: String?): Field? {
return try {
theClass.getDeclaredField(fieldName)
} catch (e: Exception) {
null
}
}
}
In my case I was dumb enough to register an adapter with X class, and try to serialize fromJson with Y class:
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Game.class, new TournamentSerializer());
final Gson gson = gsonBuilder.create();
createdTournament = gson.fromJson(jsonResponse.toString(), Tournament.class);
For Kotlin-er:
val fieldsToExclude = listOf("fieldToExclude", "otherFieldToExclude")
GsonBuilder()
.setExclusionStrategies(object : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes?) = f?.let { fieldsToExclude.contains(it.name) } ?: false
override fun shouldSkipClass(clazz: Class<*>?) = false
})
.create()

Java Reflection - listing properties (getters & setters) of a class

public class foo
{
private String _name;
private String _bar;
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
public String getBar() {
return _bar;
}
public void setBarn(String bar) {
_bar = bar;
}
}
If I have the above class can I use reflection to list the properties defined by the getters and setters? I've tried the method below but it doesn't work, Field[] fields is left empty. I know I can do this in .Net but Java is a very different animal. Am I barking up the wrong tree altogether?
private HashMap<String, String> getHashMap(Object obj) {
HashMap<String, String> map = new HashMap<String, String>();
Class<?> cls = obj.getClass();
Field fields[] = cls.getFields();
for(Field f : fields) {
String name = f.getName();
String value = f.get(obj).toString();
map.put(name, value);
}
return map;
}
Also setters and getters maybe evil, should I just drop this?
Maybe use cls.getDeclaredFields instead ? (And f.setAccessible(true) before get private field).
If you want getter and setter you have to get method by getDeclaredMethods. Then I suggest using BeanUtils instead of writing your own reflection logic :) (IMHO less convenient is java.beans.Introspector).
Use the Introspector class. Obtain the BeanInfo and use getPropertyDescriptors() method. That should get you on the way.
You can do something like this:
List<Method> methods = Arrays.asList(getClass().getDeclaredMethods());
for (Method m : methods)
{
String name = m.getName();
if (name.startsWith("get") || name.startsWith("is"))
{
// Do something with the getter method
} else if (name.startsWith("set"))
{
// Do something with the setter method
}
}

Categories

Resources