简体   繁体   中英

Java IntelliJ IDEA Serialization UnusedDeclaration inspection error

I am fixing and cleaning up my school project and we are supposed to use the "InspectCode" feature in IntelliJ IDEA. We are to fix all warnings before returning the project. I got some warnings under a category "Declaration redundancy/unused declaration. This is the warning category definition:

"This inspection reports classes, methods or fields in the specified inspection scope that are not used or not reachable from entry points."

I don't understand why. I have a total of four warnings that are connected to my serialization code ( see code below). The project works fine and I get no errors. I am asking for help to understand and hopefully be able to remove these four warnings.

private void readObject(ObjectInputStream is) throws ClassNotFoundException, IOException {
// default de-serialization
is.defaultReadObject();
quests = new ArrayList<>();

QuestManager qm = (QuestManager) is.readObject();

for (String name : qm.questNames) {
    quests.add(QuestBank.getQuest(name));
}

for (Quest q : quests) {
    System.out.println("Quest name: " + q.name);
}
}

This is one of the classes that raises the error: "Method is never used" Both methods raises that warning.

As I said before everything works. I know these two methods are being called because I have tested to remove them and also att System.out.println(anytexthere) and that is called.

I wonder if I am supposed to mark them or call them seperately or something else.

Thanks in advance.

This is the way the Java serialization mechanism works.

There are some APIs such as readObject that are called reflectively by the serialization mechanism. They are required to be declared private , however. When looked at from the point of view of just the programming language, it is a private method that is never referenced anywhere else from within this class, therefore, it must be unused. Perhaps this is what IntelliJ is doing. It apparently isn't taking the reflective nature of serialization into account. This would have to be special-cased in any kind of static analysis.

As far as I can see there is nothing wrong with your code. This is just how the serialization mechanism works in Java.

There may be some kind of annotation that can be added (like @SuppressWarnings ?) or option that can be set in IntelliJ to avoid this kind of warning.

(You mentioned "both methods" but I see only one method here, readObject . I presume the other method is writeObject , which is called the exact same way by the serialization mechanism, and will result in the same kind of warnings.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM