A life committed to learning.

Where’s my Java reflection?, Part II

Just to give the final implementation started in “Where’s my Java reflection“, here it goes the implementation of the generator for the method bindErrors (check last post “Where’s my Java reflection” to get into context):

private void composeBindErrorsMethod(TreeLogger logger,
			SourceWriter sourceWriter, TypeOracle typeOracle) {

		sourceWriter.println("public void bindErrors("
				+ parameterizedType.getQualifiedSourceName()
				+ " object, Map<String, List<String>> errors) {");

		// Get the fields declared in the parameterized type
		JField[] fields = parameterizedType.getFields();
		for (JField field : fields) {

			JClassType classType = field.getType().isClass();
			if (classType != null) {

				JClassType erroableType = typeOracle.findType(Errorable.class

				if (classType.isAssignableTo(erroableType)) {

					sourceWriter.println("if (errors.containsKey(\""
							+ field.getName() + "\")){");
					sourceWriter.println("object." + field.getName()
							+ ".setErrors(errors.get(\"" + field.getName()
							+ "\"));");



Again, hope it helps anyone.



View more posts from this author
2 thoughts on “Where’s my Java reflection?, Part II
  1. Cesar Alvernaz

    Hi Joao 🙂

    From languages that I’ve already did some stuff, Java is undoubtedly the easiest and expressive API (mostly), but in the particular case of reflection I can’t share the same opinion. It is a very powerful and useful mechanism, but the way how is exposed is awful. It turns out that, to make generic and clean code using reflection we break the most important rule in programming, readability.

  2. joaomrpereira

    Hi Cesar, how’re doing?

    I like it and generally reflection is used to implement some kind of framework code, i.e., you build a framework to do validations for example, then you’ll expose it though an API to the world and they don’t even know that the API was implemented with reflection… now, if you ever see reflection being used directly in you business logic, well….


Leave a Reply

Your email address will not be published. Required fields are marked *