Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Runtime API to find if the object is serialzable or not

 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do we have any api which would tell us in runtime whether the object is serelizable or not?

something like this...

i am receiving object reference runtime which i am not aware whether is is serializable or not...

is there any way to find it out?


baseClassReference = ObjectReceivedByRuntime;


http://www.coderanch.com/t/417840/java-programmer-SCJP/certification/Serializable-issues
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the instanceof operator to determine if an object implements Serializable just as you would to determine class and inherited types.

Naturally you are depending on the designer of the class to use the Serializable marker interface correctly.

Bill
 
K Abhijit
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;



class Base implements Serializable{

// assume this class is serializable

}

class Derived extends Base {

Connection con = null;
InputStream in =null;
// is thi class serializable too? noway... as input stream and connection are not serializable object...
// but System.out.println(b instanceof Serializable); == true;


}
public class TestSerializableSubClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Base b = new Derived();
System.out.println(b instanceof Serializable);

}

}


please advise ......
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Advise? Like I said - you depend on the designer to use Serializable correctly.

You could try writing the object to an ObjectOutputStream - an exception you could catch would be thrown.

Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic