Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java access Integer constructor through reflection

Tags:

java

I'm having this code. Why doesn't it works?(Working meaning that it display 3) How can I fix it?

public class Main {
    public static<V> V copy(V var){
        try{ 
            return (V) var.getClass().getConstructor(var.getClass()).newInstance(var);
        }
        catch(Exception e){
            System.out.println("Copy faield " + e.getMessage() + " ");
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Integer a = new Integer(3);
        Integer b = copy(a);

        System.out.println(a);
        System.out.println(b);


    }
}

This is the output:

 Copy faield java.lang.Integer.<init>(java.lang.Integer) 
    java.lang.NoSuchMethodException: java.lang.Integer.<init>(java.lang.Integer)
        at java.lang.Class.getConstructor0(Class.java:2818)
        at java.lang.Class.getConstructor(Class.java:1723)
        at Main.copy(Main.java:7)
        at Main.main(Main.java:19)
    3
    null

Thanks!

like image 922
yonutix Avatar asked Jan 07 '15 13:01

yonutix


People also ask

How do you call a private constructor from a reflection?

Reflection API can make accessible its private constructor by calling setAccessible(true) on its Constructor instance and using newInstance() we can instantiate the class. Find the sample class which has two private constructors, one accepts no arguments and second access two arguments.

Is it good practice to use reflection in Java?

It is generally a bad idea to use reflection is application code, because you lose the strict type checking of the language. Reflection is generally for use by framework code, where it is essential. Good vs bad are not absolutes, but must be assessed in context.

What is Refelection Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

How do you find the class object of associated class using reflection?

8. How to get the class object of associated class using Reflection? Explanation: forName(String className) returns the Class object associated with the class or interface with the given string name.


1 Answers

The problem here is the distinction between:

Integer.class
int.class

The constructor for Integer takes an int parameter, not an Integer.

To get your magic method to work, you would need to do a special check of the type, and if it's a wrapper class, actually look for a constructor whose parameter is the corresponding primative type.

AFAIK there's no built in way to get the primatove class from the wrapper class - you could use a map and populate it with the mappings:

private static final Map<Class<?>, Class<?>> MAP = new HashMap<>() {{
    put(Integer.class, int.class);
    put(Long.class, long.class);
    // etc
}};

Then in your method:

Class<?> type = MAP.containsKey(var.getClass()) ? MAP.get(var.getClass()) : var.getClass();
return (V) var.getClass().getConstructor(type).newInstance(var);

It's OK to pass the int as an Integer in the parameter value - that at least gets auto unboxed.

like image 156
Bohemian Avatar answered Oct 05 '22 18:10

Bohemian