When Java class is instance of Serializable

蹲街弑〆低调 提交于 2019-12-04 07:12:44

You do this:

File generatedFile = new File(...);

This created an instance of the class File.

generatedFile.getClass()

This got the Class object for the File object, an object of type Class<File>

The documentation of File describes the class:

All Implemented Interfaces: Serializable, Comparable

If you'd like to achieve that you want to parse a java source file to see if it implements Serializable, you should get an appropriate tool for this, build the abstract syntax tree of the file in question, and extract the information from there.

Or you could just do it like this, using the isAssignableFrom method of the Class class:

public boolean checkSerializable(Class<?> classToCheck) {
    return Serializable.class.isAssignableFrom(classToCheck);
}

And then check the class itself:

boolean isSerializable = checkSerializable(MyTestTableDto.class);

This is because you call instanceof on Class object, which is serializable.

getClass returns a Class<T> object, where T is the type of the class. Because Class is defined as

public final
class Class<T> implements java.io.Serializable,
                          java.lang.reflect.GenericDeclaration,
                          java.lang.reflect.Type,
                          java.lang.reflect.AnnotatedElement 
{
  ...
}

it's clearly serializable.

The statement

assertTrue( generatedFile.getClass() instanceof Serializable );

is returning true, because this will check whether the runtime class of this generatedFile Object is an instance of Serializable or not. And the class object is serializable.

From your code, the below call will return Class instance for File object, not MyTestTableDto

generatedFile.getClass()

(removed the wrong statement)

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