Record cannot get parameter names from constructors?

10

Looking to see how to use Records with reflection under Java 16 (and 15 same behavior)

public record RecordTest2(int id, int something, double total, LocalDateTime createdOn) {

    public RecordTest2(int id, int something, double total) {
        this(id, something, total, LocalDateTime.now());
    }
}

Looking at the canonical constructor I do see the parameter names, but not in the other ones.

var recordTest2 = new RecordTest2(1, 2, 3.0, LocalDateTime.now());
Class<?> objectClass = recordTest2.getClass();

Constructor<?>[] constructors = objectClass.getConstructors();

for (Constructor<?> con : constructors) {
    System.out.println(con.getName());
    Parameter[] parameters = con.getParameters();
    for (Parameter parameter : parameters) {
        System.out.printf("param: %s\n", parameter.getName());
    }
}

output:

net.sf.persism.dao.records.RecordTest2
param: arg0
param: arg1
param: arg2
net.sf.persism.dao.records.RecordTest2
param: id
param: something
param: total
param: createdOn

Any work-around to this?

Edit: Just to dot the "I" here. I can use the @ConstructorProperties annotation from java.beans.

Share
Improve this question
15
  • 1
    I do realize that I could use javac -parameters but shouldn't this be a default anyway now? – sproketboy Apr 10 at 18:56
  • This works fine for me on Eclipse. How are you compiling your program? – Sotirios Delimanolis Apr 10 at 19:16
  • 3
    It doesn't really matter if it behaves differently on a particular IDE. Nobody is going to ship Eclipse along with Java to make it "work". – Aniket Sahrawat Apr 10 at 20:44
  • 1
    In JShell, the parameters are printed with their names – Yassin Hajaj Apr 11 at 14:37
  • 1
    @YassinHajaj That's true. Interestingly on the same version of the JDK, the javac followed by java works differently from how jshell does! – Naman Apr 11 at 18:02

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue