This might be a stupid question but I gotta know if there is a way to send the instance of a object to a method?
Like this:
public class TestClass
{
public TestClass()
{
//Initialize
}
}
public class AnotherClass
{
Instance!? mInstance;
public AnotherClass(Instance!? instance)
{
mInstance = instance;
}
public boolean isInstanceOfTestClass()
{
return mInstance == TestClass;
}
}
public class Main
{
public static void main(String[] args)
{
AnotherClass a = new AnotherClass(TestClass);
if(a.isInstanceOfTestClass)
System.out.println("lala");
}
}
(Tried to make it wrapped as codeblock)
There's no such thing as an "instance of an object". An object is an instance of a class - so "instance" and "object" refer to the same thing.
You can use the instanceof
operator to test if an arbitrary object is an instance of a particular class:
if (a instanceof AnotherClass) {
// ...
}
There's also the class java.lang.Class
, which represents the class of an object. You can get it by calling getClass()
on an object:
Class<?> cls = a.getClass();
See the API documentation of java.lang.Class
.
Well you can use Class.isAssignableFrom
and construct with an instance of Class where T is the class you want to test for.
But if you are bothered about about enforcing typing and making non-type specific classes I suggest you read up on generics.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.