How to know the type of an object Inside a function?

D

Deb

Suppose there is a finction as below where I am passing an Object.
How can I know (Inside the Function) what is the type of the Object
passed.. I mean if its an int or vector or arraylist...

function testfn(Object obj)
{
<Function BODY>
I have tto determine the type of the object HERE...
}
 
N

Noodles Jefferson

Deb said:
Suppose there is a finction as below where I am passing an Object.
How can I know (Inside the Function) what is the type of the Object
passed.. I mean if its an int or vector or arraylist...

function testfn(Object obj)
{
<Function BODY>
I have tto determine the type of the object HERE...
}

Make the argument be that type

public void dudesFunction(String s) {

//stuff to do with the string goes here.

}

Now you already know that the type is because it can't be any other
type.

--
Noodles Jefferson
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM

NP: "Icicle" (Tour Rehearsal) -- Tori Amos

"Our earth is degenerate in these latter days, bribery and corruption
are common, children no longer obey their parents and the end of the
world is evidently approaching."
--Assyrian clay tablet 2800 B.C.
 
S

shruds

Deb said:
Suppose there is a finction as below where I am passing an Object.
How can I know (Inside the Function) what is the type of the Object
passed.. I mean if its an int or vector or arraylist...

function testfn(Object obj)
{
<Function BODY>
I have tto determine the type of the object HERE...
}

use the getClass() function on the object, it'll give u the class the
object belongs to :
function testfn(Object obj)
{
Class c = obj.getClass();

String className = c.toString();

}
there it is , className hold sthe information u need.
 
R

Roedy Green

function testfn(Object obj)
{
<Function BODY>
I have tto determine the type of the object HERE...
}
you don't normally write code like that in Java. Instead you write
several versions of testfn and let java select the most appropriate
one either at compile time (with slightly different signatures) or at
run time with identical signatures, but different handling for
different subclasses.

But if you insist on coding as if Java were C, see
http://mindprod.com/jgloss/instanceof.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top