java如何获取值,如何获取值的类型(Java)

The solutions I've seen online make sense; if you know the type of the variable, then you know the type of its value. Java makes it that way; however, if I have a system of inherited classes such as this ...

DynastyPQ (base class)

FirstPQ (inherited class)

And create the objects in this manner ...

DynastyPQ pq = new FirstPQ();

Is there a way to get the type of FirstPQ so that I can use it in a cast so that I can access the class's exclusive methods? Maybe something akin to this?

(typeof(pq's value)pq).exclusiveMethod()

解决方案

You have a few options.

You could use reflection

You could use instanceof

You could use the visitor pattern

For these examples, we will attempt to find the type of this variable:

Object obj = new TargetType();

We want to see if the object referenced by obj is of type TargetType.

Reflection

There are a couple ways you could do this:

if(obj == TargetType.class) {

//do something

}

The idea behind the code above is that getClass() returns a reference to the Class object used to instantiate that object. You can compare the reference.

if(TargetType.class.isInstance(obj)) {

//do something

}

Class#isInstance checks to see if the object value passed to method is an instance of the class we are calling isInstance on. It will return false if obj null, so no null check is needed. This requires casting to perform operations on the object.

instanceof

This one is simple:

if(obj instanceof TargetType) {

//do something

}

instanceof is part of the language specification. This returns false if obj is null. This requires casting to perform operations on the object.

Visitor Pattern

I have explained this in detail in one of my other answers. You would be in charge of handling null. You should look deeper into the pattern to see if it's right for your situation, as it could be an overkill. This does not require casting.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值