简体   繁体   中英

Getting the actual class of a message body

I'm passing a List of different objects to a camel route. I would like the route to split the body into one object per message and put the class of the body in a header (using a processor).

    from("direct:in")
        .split(body())
        .process(new JmsTypeHeaderProcessor(body().getClass().getName()))
        .to("mock:out");

I'm trying it like this...

@Produce(uri = "direct:in") private ProducerTemplate template;
@EndpointInject(uri = "mock:out") private MockEndpoint endpoint;

@Test
public void testRoute() throws Exception {
    List<Object> list = new ArrayList<>();
    list.add("String");
    list.add(Integer.valueOf(1));
    list.add(Boolean.FALSE);

    template.sendBody(list);

    for (Exchange ex : endpoint.getExchanges()) {
        System.out.println("JMSType=" + ex.getIn().getHeader("JMSType"));
    }
}

When I run that I find I actually have the headers

JMSType=org.apache.camel.builder.ValueBuilder

JMSType=org.apache.camel.builder.ValueBuilder

JMSType=org.apache.camel.builder.ValueBuilder

whereas I expected, and would like

JMSType=java.lang.String

JMSType=java.lang.Integer

JMSType=java.lang.Boolean

What is needed to get the class of the actual body?

BTW. I can see that log("body.class") returns what I want but I have not been able to follow how it works or adapt it for my needs.

The Camel routes are designed in the route builder and the code is run once, to setup the routes.

So this code

.process(new JmsTypeHeaderProcessor(body().getClass().getName()))

Is invoked once, and body().getClass() returns the ValueBuilder as that is what is used at design time in the DSL to specify body etc.

If you want to access the runtime message body, then get that from the Exchange from the process method of your processor. That is the runtime message and then you can get the body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM