Skip to content

Commit

Permalink
Merge pull request #209 from maven-nar/stringify-compiler
Browse files Browse the repository at this point in the history
Make Compiler implement the toString() method
  • Loading branch information
ctrueden committed Mar 22, 2016
2 parents 203b62a + e401792 commit be7f9b3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/main/java/com/github/maven_nar/Compiler.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
Expand Down Expand Up @@ -628,4 +629,9 @@ public final CompilerDef getTestCompiler(final String type, final String output)
public final void setAbstractCompileMojo(final AbstractCompileMojo mojo) {
this.mojo = mojo;
}

@Override
public String toString() {
return NarUtil.prettyMavenString(this);
}
}
29 changes: 29 additions & 0 deletions src/main/java/com/github/maven_nar/NarUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
Expand All @@ -39,6 +40,7 @@
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.Commandline;
Expand Down Expand Up @@ -656,6 +658,33 @@ public static void runRanlib(final File file, final Log log) throws MojoExecutio
}
}

/**
* Produces a human-readable string of the given object which has fields
* annotated with the Maven {@link Parameter} annotation.
*
* @param o The object for which a human-readable string is desired.
* @return A human-readable string, with each {@code @Parameter} field on a
* separate line rendered as a key/value pair.
*/
public static String prettyMavenString(final Object o) {
final StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName() + ":\n");
for (final Field f : o.getClass().getDeclaredFields()) {
if (f.getAnnotation(Parameter.class) == null) continue;
sb.append("\t" + f.getName() + "=" + fieldValue(f, o) + "\n");
}
return sb.toString();
}

private static Object fieldValue(final Field f, final Object o) {
try {
return f.get(o);
}
catch (final IllegalArgumentException | IllegalAccessException exc) {
return "<ERROR>";
}
}

private NarUtil() {
// never instantiate
}
Expand Down

0 comments on commit be7f9b3

Please sign in to comment.