Skip to content

[proposal] check class name against keywords and java.lang #71

@guiguilechat

Description

@guiguilechat

Keywords

see #70 for the keywords

java.lang

Issue

This is an issue because this package is already imported and as such not referenced to.

Typically if I create a my.package.Object class and then I create a method

@Override
boolean equals(java.lang.Object other) 

The object other actually refers to the class I am crating, and not the java.lang.Object class.
This issue literally happened to me when compiling against a openapi web service that produces "Object" responses.

Detection

This issue is very complicated : since the java reflection works bottom-up, that is the classes know their package but the package doesn't know its classes, it's difficult to find if the class exists without a java.lang.class.forName("java.lang."+sName), with trycatch around. This expensive call requires to cache the result in a hasmap<String, Boolean>

here is my code

private static final HashMap<String, Boolean> resolvedJavaLangNames = new HashMap<>();

     /**
 * check if a name already represents a class in the java.lang package. eg
 * String should return true, but LeetH4X0R should not.
 * 
 * @param className
 *          name to test
 * @return the existence of such a class in the java.lang (cached)
 */
public static boolean isJavaLangClass(String className) {
	if (resolvedJavaLangNames.containsKey(className)) {
		return resolvedJavaLangNames.get(className);
	}
	boolean isJavaLang = true;
	try {
		Class.forName("java.lang." + className);
	} catch (Exception e) {
		isJavaLang = false;
	}
	resolvedJavaLangNames.put(className, isJavaLang);
	return isJavaLang;
}

Looking at how fast it is to use JCodeModel, I consider the use of synchronization to be worthless (I usually don't and thus would have synced over the hashmap in the method)

It should check for specific exception (security exception means I can't tell)

Reaction

In the case the class C is in java.lang already, two possibilities :

  • internally mark the class C as javaLangMisleading, so that all call to a java.lang.C are specifically written as such
  • throw an exception (bad - unless in the option)

IMO both should be available. mark the class C as misleading , AND allow users to avoid this with a compilation option.

Especially, I'm not sure how to make the misleading part, since the writing of the class names may be done without the knowledge of where that name is used.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions