byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

Please help, how to achieve this function

Open jmilktea opened this issue 2 years ago • 3 comments

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?

jmilktea avatar Jul 05 '23 07:07 jmilktea

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 avatar Jul 06 '23 09:07 raphw

@raphw Thanks for your reply. But I still can't write the code, can you give me sample code, or some reference material?

jmilktea avatar Jul 06 '23 11:07 jmilktea

Have you tried something?

raphw avatar Jul 10 '23 21:07 raphw