davidbaguetta
davidbaguetta

Reputation: 532

How to get a hash of a Java class' structure?

Imagine I have the following two classes:

public class A {
    private String field1;
    private B field2;
}

public class B {
    private String field3;
}

What I want to do is use Java Reflection to get all the fields and all the subfields from class A and create a hash out of it. In this example, I would get, say, a list of Strings saying ["field1", "field2", "field3"], and I would hash the entire list.

In case it helps, the reason I am doing this is because I have a MongoDB collection for A. However, every once in a while, I add new fields to A or B, and I need to refresh the entire collection with the new fields when that happens. For this, I need to keep track, in a separate collection, of whether I have already refreshed A's collection yet or not for its current structure. The easiest way would be to just hash its fields and subfields names.

Upvotes: 3

Views: 965

Answers (1)

Freiheit
Freiheit

Reputation: 8767

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/FieldUtils.html#getAllFieldsList-java.lang.Class- sounds like it could be a sufficient solution to your problem.

Addresssing a comment, getAllFieldsList returns List<Field> so you should be able to iterate or recurse through that List and then call Field.getType() which returns Class. Now call getAllFieldsList again. This should let you traverse from Class A then get information about Class B.

Another idea might be to use the JSON_STYLE and call https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html#ReflectionToStringBuilder-java.lang.Object-org.apache.commons.lang3.builder.ToStringStyle-. This will recurse and print out JSON representing A then you can parse the JSON and check the field names.

Another pathway might be to handle this at compile time or package time. Unless you're using other reflection or aspect oriented programming techniques your classes will only change in development at compile time. Detecting changes as part of your build or CI/CD processes then feeding those into your MongoDB may make more sense.

Upvotes: 2

Related Questions