2 * JavaInspect - Utility to visualize java software
3 * Copyright (C) 2013-2018, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 3 of the GNU Lesser General Public License
7 * or later as published by the Free Software Foundation.
10 package eu.svjatoslav.inspector.java.structure;
12 import java.lang.reflect.Field;
13 import java.lang.reflect.Method;
17 * Describes single class instance
19 public class ClassDescriptor implements GraphElement, Comparable<ClassDescriptor> {
21 private static final int MAX_REFERECNES_COUNT = 10;
22 final List<ClassDescriptor> interfaces = new ArrayList<>();
23 private final Map<String, FieldDescriptor> nameToFieldMap = new TreeMap<>();
24 private final SortedSet<MethodDescriptor> methods = new TreeSet<>();
25 private final ClassGraph classGraph;
29 ClassDescriptor superClass;
30 private String fullyQualifiedName;
32 * Incoming arrows will have this color.
34 private String distinctiveReferenceColor;
35 private String interfaceColor;
36 private String superClassColor;
37 private boolean isShown = true;
39 * Amount of field and method references pointing to this class.
41 private int referencesCount = 0;
43 // for interface, counts amount of found implementations
44 private int implementationsCount = 0;
46 // counts amount of times this class is extended
47 private int extensionsCount = 0;
49 private ClassDescriptor arrayComponent;
51 public ClassDescriptor(final ClassGraph classGraph) {
52 this.classGraph = classGraph;
55 protected void analyzeClass(final Class<?> clazz) {
57 fullyQualifiedName = clazz.getName();
59 isArray = clazz.isArray();
62 final Class<?> componentType = clazz.getComponentType();
63 arrayComponent = getClassGraph().getOrCreateClassDescriptor(
67 // System.out.println("class: " + fullyQualifiedName);
69 isEnum = clazz.isEnum();
71 isInterface = clazz.isInterface();
77 indexFields(clazz.getDeclaredFields());
78 indexFields(clazz.getFields());
79 } catch (NoClassDefFoundError error) {
80 // TODO: better logging of this error
81 System.out.println(error.toString());
86 for (final Class interfaceClass : clazz.getInterfaces()) {
87 final ClassDescriptor interfaceClassDescriptor = getClassGraph()
88 .getOrCreateClassDescriptor(interfaceClass);
89 interfaceClassDescriptor.registerImplementation();
90 interfaces.add(interfaceClassDescriptor);
93 superClass = getClassGraph().getOrCreateClassDescriptor(
94 clazz.getSuperclass());
95 if (superClass != null)
96 superClass.registerExtension();
100 protected boolean areReferencesShown() {
101 return referencesCount <= MAX_REFERECNES_COUNT;
104 private void enlistFieldReferences(final StringBuffer result) {
105 if (nameToFieldMap.isEmpty())
109 result.append(" // field references to other classes\n");
110 nameToFieldMap.forEach((fieldName, field) -> result.append(field.getDot()));
113 private void enlistFields(final StringBuffer result) {
114 if (nameToFieldMap.isEmpty())
118 result.append(" // fields:\n");
121 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
123 result.append(entry.getValue().getEmbeddedDot());
126 private void enlistImplementedInterfaces(final StringBuffer result) {
127 if (interfaces.isEmpty())
131 result.append(" // interfaces implemented by class: "
132 + fullyQualifiedName + "\n");
134 for (final ClassDescriptor interfaceDescriptor : interfaces) {
135 if (!interfaceDescriptor.isVisible())
138 if (!interfaceDescriptor.areReferencesShown())
141 result.append(" " + interfaceDescriptor.getGraphId() + " -> "
142 + getGraphId() + "[style=\"dotted\", color=\""
143 + interfaceDescriptor.getInterfaceColor()
144 + "\", penwidth=10, dir=\"forward\"];\n");
148 private void enlistMethodReferences(final StringBuffer result) {
149 if (methods.isEmpty())
153 result.append(" // method references to other classes\n");
154 for (final MethodDescriptor methodDescriptor : methods)
155 result.append(methodDescriptor.getDot());
158 private void enlistMethods(final StringBuffer result) {
159 if (methods.isEmpty())
163 result.append(" // methods:\n");
166 for (final MethodDescriptor methodDescriptor : methods)
167 result.append(methodDescriptor.getEmbeddedDot());
170 private void enlistSuperClass(final StringBuffer result) {
171 if (superClass == null)
174 if (!superClass.isVisible())
177 if (!superClass.areReferencesShown())
181 result.append(" // super class for: " + fullyQualifiedName + "\n");
183 result.append(" " + superClass.getGraphId() + " -> " + getGraphId()
184 + "[ color=\"" + superClass.getSuperClassColor()
185 + "\", penwidth=10, dir=\"forward\"];\n");
188 private void generateDotHeader(final StringBuffer result) {
190 result.append("// Class: " + fullyQualifiedName + "\n");
192 result.append(" " + getGraphId() + "[label=<<TABLE "
193 + getBackgroundColor() + " BORDER=\"" + getBorderWidth()
194 + "\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n");
197 result.append(" // class descriptor header\n");
198 result.append(" <TR><TD colspan=\"2\" PORT=\"f0\">"
199 + "<FONT POINT-SIZE=\"8.0\" >" + getPackageName()
202 final String parentClassesName = getParentClassesName();
203 if (parentClassesName.length() > 0)
204 result.append("<FONT POINT-SIZE=\"12.0\"><B>" + parentClassesName
205 + "</B></FONT><br/>\n");
207 result.append("<FONT POINT-SIZE=\"25.0\"><B>" + getClassName(false)
208 + "</B></FONT>" + "</TD></TR>\n");
211 private String getBackgroundColor() {
215 bgColor = "bgcolor=\"navajowhite2\"";
218 bgColor = "bgcolor=\"darkslategray1\"";
223 private String getBorderWidth() {
225 if (!areReferencesShown())
230 protected ClassGraph getClassGraph() {
234 protected String getClassName(final boolean differentiateArray) {
235 // this is needed for nested classes
236 final String actualClassName = fullyQualifiedName.replace('$', '.');
240 // for arrays use array component instead of array class name
241 result = arrayComponent.fullyQualifiedName;
242 if (result.contains(".")) {
243 final int i = result.lastIndexOf('.');
244 result = result.substring(i + 1);
247 final int i = actualClassName.lastIndexOf('.');
248 result = actualClassName.substring(i + 1);
251 if (differentiateArray)
255 // this is needed for nested classes
256 // result = result.replace('$', '.');
260 protected String getColor() {
261 if (distinctiveReferenceColor == null)
262 distinctiveReferenceColor = Utils.getNextDarkColor();
264 return distinctiveReferenceColor;
268 public String getDot() {
275 final StringBuffer result = new StringBuffer();
277 generateDotHeader(result);
279 enlistFields(result);
281 enlistMethods(result);
283 result.append(" </TABLE>>, shape=\"none\"];\n");
285 enlistFieldReferences(result);
287 enlistMethodReferences(result);
289 enlistImplementedInterfaces(result);
291 enlistSuperClass(result);
293 return result.toString();
297 public String getEmbeddedDot() {
302 * Returns field with given name (case is ignored). Or <code>null</code> if
303 * field is not found.
305 * @param fieldToSearch field name (case is ignored)
306 * @return field matching given name
308 protected FieldDescriptor getFieldIgnoreCase(final String fieldToSearch) {
310 for (final String fieldName : nameToFieldMap.keySet())
311 if (fieldToSearch.equalsIgnoreCase(fieldName))
312 return nameToFieldMap.get(fieldName);
317 protected String getFullyQualifiedName() {
318 return fullyQualifiedName;
322 public String getGraphId() {
330 .replace("[[L", "") // array of arrays
331 .replace("[[[L", "") // array of arrays of arrays
335 private String getInterfaceColor() {
336 if (interfaceColor == null)
337 interfaceColor = Utils.getNextDarkColor();
339 return interfaceColor;
342 private FieldDescriptor getOrCreateFieldDescriptor(final Field field) {
344 final String fieldName = field.getName();
346 if (nameToFieldMap.containsKey(fieldName))
347 return nameToFieldMap.get(fieldName);
349 final FieldDescriptor newFieldDescriptor = new FieldDescriptor(this);
350 nameToFieldMap.put(fieldName, newFieldDescriptor);
352 newFieldDescriptor.analyzeField(field);
354 return newFieldDescriptor;
357 private int getOutgoingReferencesCount() {
360 // count method references
361 for (final MethodDescriptor methodDescriptor : methods)
362 result += methodDescriptor.getOutsideVisibleReferencesCount();
364 // count field references
365 for (final FieldDescriptor fieldDescriptor : nameToFieldMap.values())
366 result += fieldDescriptor.getOutsideVisibleReferencesCount();
368 // count implemented interfaces
369 for (final ClassDescriptor classDescriptor : interfaces)
370 if (classDescriptor.isVisible())
374 if (superClass != null)
375 if (superClass.isVisible())
381 private String getPackageName() {
383 final int i = fullyQualifiedName.lastIndexOf('.');
388 return fullyQualifiedName.substring(0, i).replace("[L", "");
391 private String getParentClassesName() {
392 int i = fullyQualifiedName.lastIndexOf('.');
393 final String fullClassName = fullyQualifiedName.substring(i + 1);
395 i = fullClassName.lastIndexOf('$');
398 final String parentClassesName = fullClassName.substring(0, i);
399 return parentClassesName.replace('$', '.');
402 private String getSuperClassColor() {
403 if (superClassColor == null)
404 superClassColor = Utils.getNextLightColor();
406 return superClassColor;
410 * Checks if class has field with given name (case is ignored). Returns
411 * <code>true</code> if such field is found.
413 * @param fieldToSearch field to search for (case is ignored)
414 * @return <code>true</code> if field is found.
416 protected boolean hasFieldIgnoreCase(final String fieldToSearch) {
418 for (final String fieldName : nameToFieldMap.keySet())
419 if (fieldToSearch.equalsIgnoreCase(fieldName))
425 private void hide() {
429 protected void hideClassIfNoReferences() {
433 final int totalReferencesCount = getOutgoingReferencesCount()
434 + referencesCount + extensionsCount + implementationsCount;
436 if (totalReferencesCount == 0) {
443 private void indexFields(final Field[] fields) {
444 for (final Field field : fields)
445 getOrCreateFieldDescriptor(field);
448 private void indexMethods(final Class<?> clazz) {
449 for (final Method method : clazz.getMethods()) {
450 final MethodDescriptor methodDescriptor = new MethodDescriptor(
451 this, method.getName());
453 methods.add(methodDescriptor);
455 methodDescriptor.analyze(method);
461 public boolean isVisible() {
463 if (Utils.isSystemDataType(fullyQualifiedName))
466 if (Utils.isSystemPackage(fullyQualifiedName))
469 if (!getClassGraph().isClassShown(fullyQualifiedName))
473 if (arrayComponent != null)
474 if (Utils.isSystemDataType(arrayComponent.fullyQualifiedName))
475 // Do not show references to primitive data types in arrays.
476 // That is: there is no point to show reference to byte when
477 // we have class with byte array field.
484 * Register event when another class is extending this one.
486 protected void registerExtension() {
490 protected void registerImplementation() {
491 implementationsCount++;
494 protected void registerReference() {
499 public boolean equals(Object o) {
500 if (this == o) return true;
501 if (!(o instanceof ClassDescriptor)) return false;
503 ClassDescriptor that = (ClassDescriptor) o;
505 return getFullyQualifiedName().equals(that.getFullyQualifiedName());
510 public int hashCode() {
511 return getFullyQualifiedName().hashCode();
515 public int compareTo(ClassDescriptor o) {
516 return fullyQualifiedName.compareTo(o.fullyQualifiedName);