Java compiler fails to recognise static inner class

≡放荡痞女 提交于 2019-12-05 07:56:45

The error message "an enclosing instance that contains x.y.z.Parent.DesiredClass is required" means that the compiler thinks that DesiredClass is NOT static.

I suggest that you get hold of the Parent$DesiredClass.class file, and use javap to examine the compiled classes attributes. That should tell you if the class you are compiling against is really a static inner class.

While still busy doing the low level investigations suggested by @Richard and @Stephen, I had a couple of ideas about this issue.

I first tried to extend DesiredClass with one which has a less ambiguous name and then see if it would work if I rather use the extended class. It did not and caused the same error.

I then tried to instantiate DesiredClass using Class.forName():

DesiredClass dc;
try {
    dc = (DesiredClass) Class.forName(classname).newInstance();
}
catch (Exception e) {

}

This worked!

Even though this is a bit messy, it allows me to continue with my work. I would love to know what the root cause of the error is (perhaps some problem with the class loader which the compiler uses, especially considering that there are classes which have been compiled with different "brands" of compilers?), but the cost-benefit of spending more time trying to figure this out is not worth it.

Thank you to everyone who contributed.

I suggest trying to trim this error down to the fewest possible classes.

STEP 1

Take your custom code project, and see if you can trim the offending class down to a single line of code that fails the build. Then see if you can remove all other classes from your custom project, and still fail the build.

Do a bit of renaming of methods etc in this single class, to hide the "secret" info of production code, and hopefully you will have a source file you can post on this forum.

STEP 2

Do the same for the product code that is being used (not the JAR file, the other class files).

Then for the JAR file stuff. At each point (laborious and boring), confirm you still get the same errors.

STEP 3

Hopefully it was possible to replicate this problem with 3 class files, none of which contain any production names/code etc. Post these for us to see - I think this is an interesting problem.

ymmv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!