Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get generic types as exchange input body rather than casting?

In Apache camel it's possible to get message body by it's own type by passing it's type into exchange.getIn().getBody(Class<T> type). Lets say we want to get message body as String here is the example as following:

String body = exchange.getIn().getBody(String.class);

In case of Generic or Parameterized types message, how do we get the object by it's own type rather than traditional object type casting. Here the pseudo code snippet for your realization:

package com.chorke.hmis.fusion.epoint;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.camel.Exchange;
import org.springframework.stereotype.Component;

@Component("chorkeProcessor")
public class ChorkeProcessorImpl implements ChorkeProcessor{

    @Override
    public void process(Exchange exchange) throws Exception {
        ArrayList<HashMap<String, Object>> list = null;
        list = exchange.getIn().getBody(ArrayList<HashMap<String, Object>>.class);

        for (HashMap<String, Object> map : list) {
            for (String key : map.keySet()) {
               Object value= map.get(key);
               //TODO
            }
        }
    }
}

Our expectation is as like as the example.

like image 287
Śhāhēēd Avatar asked Aug 28 '16 06:08

Śhāhēēd


1 Answers

It simply can't be done, there's no ArrayList<HashMap<String, Object>>.class class, the class is always a simple ArrayList.class, that's just how Java generic types work. You'll either have to use the plain ArrayList:

@Component("chorkeProcessor")
public class ChorkeProcessorImpl implements ChorkeProcessor{

    @Override
    public void process(Exchange exchange) throws Exception {
        ArrayList<HashMap<String, Object>> list =  exchange.getIn().getBody(ArrayList.class);

        for (HashMap<String, Object> map : list) {
            for (String key : map.keySet()) {
               Object value= map.get(key);
               //TODO
            }
        }
    }
}

OR define and use your own type that just extends ArrayList<HashMap<String, Object>>:

// MyListOfMaps.java
public class MyListOfMaps extends ArrayList<HashMap<String, Object>> {
    // constructors, additional methods
}

// ChorkeProcessorImpl.java
@Component("chorkeProcessor")
public class ChorkeProcessorImpl implements ChorkeProcessor{

    @Override
    public void process(Exchange exchange) throws Exception {
        MyListOfMaps list =  exchange.getIn().getBody(MyListOfMaps.class);

        for (HashMap<String, Object> map : list) {
            for (String key : map.keySet()) {
               Object value= map.get(key);
               //TODO
            }
        }
    }
}

You should be careful with this approach if you do not create the list of maps yourself - you may need to provide a proper converter

like image 124
Miloš Milivojević Avatar answered Nov 04 '22 14:11

Miloš Milivojević