问题描述:

I'd like to find a compile time solution to remove the finalize method of my classes according to a flag. This is to avoid performances issues with GC.

My build system is ANT.

Basically, I want the equivalent of this C-preprocessor macro:

#ifdef USE_FINALIZE

protected finalize() {

...

}

#endif

Is this possible in Java?

网友答案:

According to the javadoc

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

Which means that

a) you're not doing any special finalization unless you're explicitly declaring it in your code, and

b) If you don't include a finalize() method Object.finalize() will be called, which is no-op. So you can't improve on that unless you could somehow hack the jvm to not even call finalize.

A better question might be, do you have a specific reason to worry about finalization time in your application? have you profiled this? It's entirely possible that this is a non-issue in your application.

网友答案:

The short answer is that there is no built-in way to do this. See Java conditional compilation: how to prevent code chunks to be compiled? for more details.

However, you could potentially build a custom solution using Ant using the replace task. To do this, you could just put some magic string in comments around the blocks you want to sometimes include.

/******CONDITIONAL******

// conditional code goes here

*******CONDITIONAL*****/

Then use replace to remove those comments based on some conditional property.

网友答案:

It is perhaps possible with an annotation processor (not sure at all) at compile time, using the mirror api, but it may be hard to achieve I guess.

Perhaps it is possible at Runtime too with Javassist or CGLib

网友答案:

just use java preprocessor, for instance https://github.com/raydac/java-comment-preprocessor it supports ANT and MAVEN

相关阅读:
Top