[JAVA] Make a reflection utility ③

Introduction

This time, it is reflection using annotation. Field annotations are useful when you want to give a field a little attribute, but you don't want to write it in your business logic.

The one I made last time → Utility to fill the field of the object with an appropriate value

What I made this time

This time, I created a Util method that converts an Entity object to horizontal (1 record of CSV).

--Data annotation --AnnotationUtil class --User class --Main class

AnnotationUtil Output the header line with the getHeader method. Output a row of data with the getData method.

AnnotationUtil.java


package test1;
import java.lang.reflect.Field;

public class AnnotationUtil {
	/**comma*/
	private static final String DELIMITER = ",";
	/**Double quotation*/
	private static final String QUOTE = "\"";

	/**
	 *Convert User to CSV 1 line.<br>
	 *User has@Returns the field with Data as one CSV line.<br>
	 * isHeader=If true, title is returned in the specified CSV format.
	 */
	public static String getUser(User obj, boolean isHeader, String delimiter, String quote) {
		Field[] fieldList = obj.getClass().getDeclaredFields();
		StringBuilder sb = new StringBuilder();

		for (Field f : fieldList) {
			f.setAccessible(true);
			Data annotation = f.getAnnotation(Data.class);
			if (annotation == null) {
				continue;
			}
			String value;
			try {
				if (isHeader) {
					value = annotation.title(); //title
				} else {
					value = String.valueOf(f.get(obj)); //value
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				//Since the throws declaration is troublesome, make all exceptions at runtime
				throw new RuntimeException(e);
			}

			//When the enclosing character is specified
			if (quote != null)
				sb.append(quote);
			//Value or item name
			sb.append(value);
			//When the enclosing character is specified
			if (quote != null)
				sb.append(quote);

			//Delimiter
			sb.append(delimiter);
		}
		//Remove last delimiter
		sb.deleteCharAt(sb.length() - 1);

		return sb.toString();
	}

	public static String getHeader(User user) {
		return getUser(user, true, DELIMITER, QUOTE);
	}

	public static String getData(User user) {
		return getUser(user, false, DELIMITER, QUOTE);
	}
}

Data Add this annotation to the field to be output as CSV data. Specify the header name with title.

Data.java


package test1;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(FIELD)
@Retention(RUNTIME)
public @interface Data {
	String title();
}

User Entity class. Add Data annotation to the field you want to output.

User.java


package test1;

public class User {
	@Data(title = "Employee ID")
	public Integer id;
	@Data(title = "name")
	public String name;
	public String insertDate;
	public String insertUser;
	public String updateDate;
	public String updateUser;
}

Main For checking the operation of the utility.

Main.java


package test1;

public class Main {
	public static void main(String[] args) {
		System.out.println("### Start ###");
		User user = new User();
		user.id = 101;
		user.name = "Albert";
		user.insertDate = "20190501";
		user.insertUser = "Chris";
		user.updateDate = "20190512";
		user.updateUser = "Jill";

		System.out.println(AnnotationUtil.getHeader(user));
		System.out.println(AnnotationUtil.getData(user));
		System.out.println("### End ###");
	}

}

Execution result

python


### Start ###
"Employee ID","name"
"101","Albert"
### End ###

It has been converted from vertical to horizontal. Since Data is added only to id and name, only those two are output properly.

Afterword

At first, when I implemented it without using the IDE for the first time in a while, for some reason the return values of Field # getAnnotation () were all NULL. Why did it work when I used the IDE? ??

Recommended Posts

Make a reflection utility ②
Make a reflection utility ③
Make a reflection utility ①
[Rails] Make a breadcrumb trail
Make a rhombus using Java
Make a language! (Making a simple calculator ②)
Try to make a simple callback
Make a slideshow tool with JavaFX
Make a Christmas tree with swift
How to make a JDBC driver
Priority Queue max Make it a queue
Make a language! (JavaCC environment construction)
Make a garbage reminder with line-bot-sdk-java
Make a list map with LazyMap
A murmur about the utility class
Make a language! (Making a simple calculator ①)
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
Make a SOAP call in C #
Try to make a peepable iterator
How to make a Java array
Make a typing game with ruby
How to make a Java calendar Summary
Make a note of Ruby keyword arguments
Make a family todo list with Sinatra
How to make a Discord bot (Java)
Make a family todo list with Sinatra
Let's make a smart home with Ruby!
Make a login function with Rails anyway
Make a site template easily with Rails
[Java] Let's make a DB access library!