Java: Sending Objects via Sockets - ClassNotFoundException

Sometimes you get ClassNotFoundException in Java.

Many people, according to the found answers at google, do not understand this Exception and why this Exception getting thrown by the Compiler.

Here is a small example, maybe this helps you to understand this problem.

At first, we need to understand, "What is a package" and why we need them.

What is a package

A package is a kind of path to the specific folder. We can say, that for example on Windows its "C:\Windows\System32", on Linux it could be "/home/userX/Download". Both take a delimiter, like "\" or "/" to split every single folder from the path. In Java its similiar. There are folders too, but we call them packages.

For example, my package could be "de.fo0.blog". Every single programmer, should have his own package structure, like "location.myName.projectname", then we dont get any conflicts each other.

The next step, after we understood the package structure now, and why we need them, is to understand that all classes need a package. If not, you can not identify this class. And here we got the root cause of the problem/exception "ClassNotFoundException". If you transport objects which are classes, between two Java-Applications like Client --> Server architecture then both sides of the application needs to know, where is this object, what you send from client to server located on my side.

Bad-Example:

Client:

com.fo0.example.client.DATA

Server:

com.fo0.example.server.DATA

If we sending the DATA object from Client to Server, we would get an exception like "ClassNotFoundException". Because DATA is located in differente package structures. If you want to share this DATA object, use the same package name for that DATA object.

Good-Example:

Client:

com.fo0.example.bean.DATA

Server:

com.fo0.example.bean.DATA

Now we can share the DATA object between the two Java Applications.

I hope this helped you.

This article is my 25th oldest. It is 294 words long