Please help, how to achieve this function
I have defined an interface and want to convert the property value of the class into an array:
public interface ToArray<T> {
Object[] toArray(T data);
}
as below class:
public static class MyClass {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hope to dynamically generate this class:
public static class BdResult implements ToArray<MyClass> {
@Override
public Object[] toArray(MyClass mc) {
return new Object[]{mc.getId(), mc.getName()};
}
}
The properties of the class are dynamic, mc.getId(), mc.getName() I don't want to write hard code, so that when adding more properties later, no code needs to be modified。
how to achieve this function?
You would need to create the byte code yourself by implementing this with custom StackManipulations. In your case, it would be a ArrayCreation which entails two MethodVariableAccess with corresponding MethodInvocation, followed by a MethodReturn.
If you look around Byte Buddy's code base, you find multiple examples of it.
@raphw Thanks for your reply. But I still can't write the code, can you give me sample code, or some reference material?
Have you tried something?