Alfredo A.
Alfredo A.

Reputation: 1787

How to obtain the runtime type from an object in java

I have this code:

public void doSomething(Integer param){
.
.
.
  JAXBElement<Integer> jaxb = new JAXBElement<Integer>
                                    (new QName("uri","local"),Integer.class, param);
.
.
.
}

And I want it to be more flexible. I need the parameter to be of type Object, but I don't know how to change this line:

JAXBElement<what_do_I_put_here> jaxb = new JAXBElement<what_do_I_put_here>(new QName("uri","local"),Integer.class, param);

I want it to use the runtime class of the type stored in param

public void doSomething(Object param){
.
.
.
  JAXBElement<??????> jaxb = new JAXBElement<??????>
                                    (new QName("uri","local"),?????.class, param);
.
.
.
}

Upvotes: 0

Views: 58

Answers (1)

Nik
Nik

Reputation: 260

Not entirely sure (don't have access to an IDE at the moment) but isn't is something like

public <T extends Object> void doSomething(T param) {
    .
    .
    JAXBElement<T> jaxb = new JAXBElement<T>(new QName("uri", "local"), (Class<T>) param.getClass(), param);
    .
    .
}

Upvotes: 1

Related Questions