mahdi pishguy mahdi pishguy - 4 months ago 11
Java Question

Java get class fields on loop clause and check value

this below class in my database model on Relam object

public class ModelMarketBanners extends RealmObject {
@PrimaryKey
private String id;
private String marketId;
private String imageFileName;
private String title;
}


as far as i know i can get model fields data by class getter such as
getId()
, but i want to get filed name instead of class getter methods on loop clause, for example using
for
to show all class fields such as
id
or
marketId
, how can i do that?

i want to get all fileds data and if which one isn't empty attach layout with that data, instead of programing multi line to check and attaching that

for example:

for(int i=0; i> model.field_count; i++){
if (model.field.lenght() > 0) Log.v("data is: ", model.field);
}


instead of

SampleModel model = realm.where(SampleModel.class).findfirst();
if(model.getId().lenght() > 0)
Log.v("data is",model.getId());
if(model.getmarketId().lenght() > 0)
Log.v("data is",model.getmarketId());
if(model.getImageFileName().lenght() > 0)
Log.v("data is",model.getImageFileName());

Answer

There is a way, using reflection:

    for (Field field : ModelMarketBanners.class.getDeclaredFields()) {
        for (Method method : ModelMarketBanners.class.getMethods()) {
            if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3))) {
                if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase())) {
                    try {
                        Object value = method.invoke(model);
                        if (!TextUtils.isEmpty(String.valueOf(value)) {
                            Log.v("data is: ", String.valueOf(value));
                        }
                    } catch (IllegalAccessException | InvocationTargetException e) {
                    }

                }
            }
        }
    }