1

Let's say you have the following Java code:

public class Test {
    public Test() {
        string name = "Robot";
        Robot aRobot = new Robot();
        List<String> aList = new List<String>();
    }
}

How would you go about detecting that Test, string, List, and Robot were class names and their position in the text file?

Pointy
  • 405,095
  • 59
  • 585
  • 614
Rawr
  • 2,206
  • 3
  • 25
  • 53
  • You may want to check `JBoss Roaster` and their JDT implementation which allows you to parse java source. – rkosegi Mar 03 '16 at 05:31

2 Answers2

1
You can use Refelction API for finding the type of the field in your java file.

import java.lang.reflect.Field;
import java.util.List;

public class FieldSpy<T> {
    public boolean[][] b = {{ false, false }, { true, true } };
    public String name  = "Alice";
    public List<Integer> list;
    public T val;

    public static void main(String... args) {
    try {
        Class<?> c = Class.forName(args[0]);
        Field f = c.getField(args[1]);
        System.out.format("Type: %s%n", f.getType());
        System.out.format("GenericType: %s%n", f.getGenericType());

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    }
    }
}
Sample output to retrieve the type of the three public fields in this class (b, name, and the parameterized type list), follows. User input is in italics.

$ java FieldSpy FieldSpy b
Type: class [[Z
GenericType: class [[Z
$ java FieldSpy FieldSpy name
Type: class java.lang.String
GenericType: class java.lang.String
$ java FieldSpy FieldSpy list
Type: interface java.util.List
GenericType: java.util.List<java.lang.Integer>
$ java FieldSpy FieldSpy val
Type: class java.lang.Object
GenericType: T
Madhesh
  • 69
  • 6
  • This could work, but unfortunately I'm dealing with plain text so reflection is out of the picture :/ – Rawr Mar 03 '16 at 05:13
0

A rather hacky solution would be to put the text in a file after removing imports and with a name different from the public class

Then use the JavaCompiler package to compile the file on the fly and catch compilation errors

  1. You could catch "class not defined" type of errors for default Java classes.
  2. For classes defined by you, if it is a public class, you would get an error like "class must be defined in its own file"

So in the end you would get

  1. The line number of the class in the compilation error
  2. The name of the class in the error statement

This could be too complicated in the long run, but in the absence of libraries to do what the OP states, this could be used.

In addition, things could get tricky for classes under java.lang since they are included by default

Community
  • 1
  • 1
S Raghav
  • 1,386
  • 1
  • 16
  • 26