Skip to content

Commit f95f697

Browse files
author
Daniel Wiehl
committed
Enable reference caching for classes with are not visible to the
classloader Otherwise, when using such a class multiple times within the same JClass, that very same class is not identified as the same when building the model in the 'collecting phase'. That causes JFormatter to think that those classes collide because having the same name, although being the very same class. As a consequence, no import directive is created for that class but referenced the fully qualified way instead.
1 parent 1d954f3 commit f95f697

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

codemodel/src/main/java/com/sun/codemodel/JCodeModel.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,9 @@ public final class JCodeModel {
101101
/** All JReferencedClasses are pooled here. */
102102
private final HashMap<Class<?>,JReferencedClass> refClasses = new HashMap<Class<?>,JReferencedClass>();
103103

104-
104+
/** All JDirectClass are pooled here. */
105+
private final Map<String,JDirectClass> refDirectClasses = new HashMap<String,JDirectClass>();
106+
105107
/** Obtains a reference to the special "null" type. */
106108
public final JNullType NULL = new JNullType(this);
107109
// primitive types
@@ -382,7 +384,12 @@ public JClass ref(String fullyQualifiedClassName) {
382384
}
383385

384386
// assume it's not visible to us.
385-
return new JDirectClass(this,fullyQualifiedClassName);
387+
JDirectClass jdrc = refDirectClasses.get(fullyQualifiedClassName);
388+
if (jdrc == null) {
389+
jdrc = new JDirectClass(this,fullyQualifiedClassName);
390+
refDirectClasses.put(fullyQualifiedClassName, jdrc);
391+
}
392+
return jdrc;
386393
}
387394

388395
/**
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.sun.codemodel.tests;
2+
3+
import static org.junit.Assert.assertSame;
4+
5+
import org.junit.Test;
6+
7+
import com.sun.codemodel.JClassAlreadyExistsException;
8+
import com.sun.codemodel.JCodeModel;
9+
10+
public class JDirectClassRefTest {
11+
12+
@Test
13+
public void testDirectClassRef() throws JClassAlreadyExistsException {
14+
final JCodeModel codeModel = new JCodeModel();
15+
16+
assertSame("Should be same JClass", codeModel.ref("org.test.ClassNotOnClasspath"), codeModel.ref("org.test.ClassNotOnClasspath"));
17+
}
18+
}

0 commit comments

Comments
 (0)