mercredi 6 décembre 2017

java utility to persist a generic object using reflection

I have written a utility to persist a generic object into the database. But, when I try to persist, I am getting "NullPointer" exception as my code is getting the type rather than a class. Here is the piece of code:

public SyslogMessage save(SyslogMessage syslog) {
        MapRDBUtility<SyslogMessage> utility = new MapRDBUtility<SyslogMessage>();
            utility.save(syslog, "sample", "f");
}

@SuppressWarnings("deprecation")
public class MapRDBUtility<T> {

    @Autowired
    private HbaseTemplate hbaseTemplate;

    public T save(T clazz, String tableName, String columnFamily) {

        return hbaseTemplate.execute(tableName, new TableCallback<T>() {
            public T doInTable(HTableInterface table) throws Throwable {
                Field[] fields = clazz.getClass().getDeclaredFields();
                Put p = new Put(Bytes.toBytes(getKeyFieldName(clazz)));
                for (Field field : fields) {
                    p.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(field.getName()), Bytes.toBytes(field.getName()));
                }
                table.put(p);
                return clazz;
            }
        });
    }

    private String getKeyFieldName(T clazz) {
        String targetField = null;
        Field[] fields = clazz.getClass().getDeclaredFields();
        Pattern p = Pattern.compile("\\b" + "key" + "\\b");
        Matcher m;
        for (Field field : fields) {
            m = p.matcher(field.getName());
            if (m.find() == true) {
                targetField = field.getName();
            }

        }

        return targetField;
    }

}

I would like to get help on fixing this issue and understanding how to get a class rather than a type. Any help will be appreciated.





Aucun commentaire:

Enregistrer un commentaire