samedi 14 octobre 2017

How to tell if a primitive type was cast into an object in Java?

In Java, consider the following piece of code:

int myPrimitiveInt = 5;
Integer myObjectInt = 4;

Object fromPrimitive = myPrimitiveInt;
Object fromObject = myObjectInt;

System.out.println(fromPrimitive.getClass());
System.out.println(fromObject.getClass());
System.out.println(int.class);

And the output:

class java.lang.Integer
class java.lang.Integer
int

What I would like, is a way to get also the output int for the first println.


"WHY?", you will ask. Well, for one thing, I would just like to know if something like this is even possible.

But the actual practical reason behind this is an abstraction layer for testing private methods via reflection. The minimal code:

package testing;

import java.lang.reflect.Method;

public class Testing {
    private static void doStuff(int a) {
        System.out.println("primitive: " + ((Object) a).getClass());
    }

    private static void doStuff(Integer a) {
        System.out.println("object: " + ((Object) a).getClass());
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        Reflect.reflect(Testing.class, "doStuff", 10);
    }
}

abstract class Reflect {
    static Object reflect(Class<?> clazz, String methodName, Object arg) throws ReflectiveOperationException {
        Method method = clazz.getDeclaredMethod(methodName, arg.getClass());
        method.setAccessible(true);
        return method.invoke(null, arg);
    }
}

The output:

object: class java.lang.Integer

Expected output:

primitive: class java.lang.Integer

Or even better (if possible at all):

primitive: int

Note: I know I can do clazz.getDeclaredMethod(methodName, int.class). The whole point of this post is to make this procedure more abstract. Please do not give me answers suggesting to pass the argument types to the reflect method!





Aucun commentaire:

Enregistrer un commentaire