How to set reflected Fields directly to an instance of Object?

Viewed 36

I have a problem setting Fields (java.lang.reflect) from POJO to an instance of the Object class.

The examples I've come across on the internet all use setting those Fields to an instance of a concrete class. Since the situation is such that I need a class to have different properties each time, I definitely can't write any classes where I would set those fields. The only logical approach I can think of would be to use an Object class.

To not dive any deeper, what I'm trying is to use this class:

class Apple {
    private String color;
    private Double weight;
    private Date order;
    
    //default constructor
    //getters + setters
}

and let's say use its field color to construct a new class containing only that property.

class Test {
    public static void main(String[] args) {
        Apple apple = someDatabase.findApple();

        Field field = apple.getClass().getDeclaredField("color");
        field.setAccessible(true);

        Object value = field.get(apple);

        Object dummy = new Object();
        field.set(dummy, value); //Says: "Cannot set String field to java.lang.Object"
    }
}

If this can't be done this way, may someone recommend another solution for this problem?

1 Answers

Just get the constructor via reflection, invoke it, then set the fields.

Apple apple = someDatabase.findApple();

Field field = apple.getClass().getDeclaredField("color");
field.setAccessible(true);

Object value = field.get(apple);

Constructor<? extends Apple> appleCtor = apple.getClass().getDeclaredConstructor();
appleCtor.setAccessible(true);

Apple dummy = appleCtor.newInstance();
field.set(dummy, value);
Related