How does java use generics to extract a common static method that converts a DTO class to a VO class?

my colleague offered a solution, but it wasn"t quite what I wanted, so I came to ask

the method that my colleague told me

public static <DTO, VO> VO getVO(DTO dto, Function<DTO, VO> function){
    return function.apply(dto);
}

:

getVO(new TestDTO(),TestVO::new);

the colleague"s method is probably the most perfect; there is no need to modify the VO class and the DTO class, but I have a bit of an axis. I want to know another way, and I don"t have the heart to keep pestering my colleagues to ask,

.

the method I want:

public static <DTO,VO>VO getVO(DTO dto){
    return new VO(dto);
}

:

getVO(new TestDTO());

VO class:

public class TestVO {
    private String name;

    public TestVO(TestDTO dto) {
        this.name = dto.getName();
    }
}

DTO class

public class TestDTO {
    private String name;

    public String getName() {
        return name;
    }
}

so I would like to ask you, in the way I want, how to modify the code to achieve it?

public static <DTO,VO>VO getVO(DTO dto){
    return new VO(dto);
}

static check error:

Type parameter "VO" cannot be instantiated directly

the way I want to use it is to make a static class accept a generic type, and then call the getVO method,

public class VOUtil<VO>{
    public static <DTO>VO getVO(DTO dto){
        return new VO(dto);
    }
} 

is used as follows:

VOUtil<TestVO>.getVO(dto);

is this all right?

Jun.04,2021

the ideal is plump, and the reality is bony. The following quote ( "Core Java"-- 10th Edtion ) should give you answers, reasons and suggestions:

Menu