Jump to content

java question

digitalMaster

hello,

i cant understand what is this

 

if (Class.forName(className).isInstance(obj)) 

 

 

how can i use this statement in a method Print(className) and when the user gives the appropriate class name the method will works?(sry for bad english)
Link to comment
Share on other sites

Link to post
Share on other sites

 

hello,

i cant understand what is this

 

if (Class.forName(className).isInstance(obj)) 

 

 

how can i use this statement in a method Print(className) and when the user gives the appropriate class name the method will works?(sry for bad english)

 

 

Well, when in doubt it is always handy to look at the oracle docs about each method, if you need the answer more quickly :P I will discuss it below, but just as a handy help as well here are the two links I used to get the answer ( http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInstance%28java.lang.Object%29 )

 

 

Anyways to answer it more fully

forName will take a string, and it will return a class object which is whatever type the string was.  The example in the doc is Class.forName("java.lang.Thread") which basically returns a Thread object.

Now for the isInstance.  The isInstance will take any object it is given and tell you true if the object is actually the same type of object.

 

An concrete example

if(Class.forName("java.lang.Thread").isInstance(new Thread())) ///would be trueif(class.forName("java.lang.Thread").isInstance(new int()) //would be false

For your other question I am not quite sure I fully understand what you are asking.  If you want it so a method will only work when an user puts in a valid class name, you would just need to use an try statement.  If Class.forName throws an ClassNotFoundException on a given "class name" the you know that the class doesn't exist.

0b10111010 10101101 11110000 00001101

Link to comment
Share on other sites

Link to post
Share on other sites

The isInstance will take any object it is given and tell you true if the object is actually the same type of object.

It also takes inheritance into account

Class.forName("javax.swing.JTextField").isInstance(new JPasswordField()); //trueClass.forName("javax.swing.JPasswordField").isInstance(new JTextField()); //false

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×