say there are 2 classes...
public class NotAbstract1 extends AnAbstract {
NotAbstract1() { super(); }
}
public class NotAbstract2 extends AnAbstract {
NotAbstract2() { super(); }
}
public abstract class AnAbstract {
AnAbstract() { //do something }
abstract void saySomething() { System.out.println("Something"); }
}
In this example, NotAbstract1
and NotAbstract2
can call saySomething()
. How can I, from within the saySomething()
method of AnAbstract
, recognize the class which called it? Without passing in the class or an identifier .
Again, the easy solution is to change the method signature to be saySomething(Class clazz)
but I'd like to not do that. I have a feeling it can be done with reflection so I'm adding that tag to the question.
您可以在saySomething()
this.getClass()
处调用saySomething()
- 它会返回当前实例的类型 - notAbstract1
或notAbstract2
。
First of all, this line will not compile:
abstract void saySomething() { System.out.println("Something"); }
You cannot both use abstract
modifier and provide a method body.
For printing the caller's class, you can write:
void saySomething() {
System.out.println(this.getClass().toString());
}
The abstract keyword in
abstract void saySomething();
is a place holder. There cannot be code associated with it. What it does is ensure that
public class NotAbstract1
public class NotAbstract2
both have a real implementations like so
public class NotAbstract1 extends AnAbstract {
void saySomething() {
System.out.println("I'm NotAbstract1");
}
}
public class NotAbstract2 extends AnAbstract {
void saySomething() {
System.out.println("I'm NotAbstract2");
}
}
The compiler does these verifications that the saySomething()
method exists in the sub classes when you compile NotAbstract1
and NotAbstract2
.
When you are holding a
AnAbstract object = .... get it from somewhere ...
You will be holding either a NotAbstract1
a NotAbstract2
or some other subclass of AnAbstract
, but you will be holding as an AnAbstract
type.
When you call
AnAbstract object = .... get it from somewhere ...
object.saySomething();
If the object was originally constructed as a NotAbstract1
you would run
System.out.println("I'm NotAbstract1");
If the object was originally constructed as a NotAbstract2
you would run
System.out.println("I'm NotAbstract2");
If the object was some other kind of AnAbstract
you would run whatever was in that sub-class's definition of saySomething()
.
尽管您可以在 saySomething() 中使用 this.getClass() 进行检查,但是如果您想根据从哪个类调用此方法来使该方法具有不同的行为,则理想情况下应该覆盖这些类中的 saySomething() 方法。
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.