[英]Jython: Check for a Java object type
I have two Java classes Foo
and FooBar
under some package.我在某个包下有两个Java 类Foo
和FooBar
。 Both of these classes implement interface FooIFC.这两个类都实现了接口 FooIFC。 I want to find if the instance is of type Foo
or FooBar
from a Jython script.我想从Jython脚本中查找实例是Foo
类型还是FooBar
类型。
I have a static getinstance()
in one of the base class(implementors) of IFC我在 IFC 的基类(实现者)之一中有一个静态getinstance()
from package import FooIFC
from package import Foo
if FooIFC.getinstance() instanceof Foo:
print "Foo"
else:
print "FooBar"
I also tried isintance(FooIFC.getinstance(), Foo)
as well .我也试过isintance(FooIFC.getinstance(), Foo)
。 Which give an error name not found.其中给出了未找到的错误名称。
instanceof
give expecting colon error. instanceof
给出预期的冒号错误。
How do I find the object type from a python script?如何从 python 脚本中找到对象类型?
There is no instanceof
operator in python, instead there is the isinstance
(that is isin s tance) builtin function.没有instanceof
在蟒蛇操作,取而代之的是isinstance
内置函数(即ISIN小号,孟清湘)。 Thus:因此:
from package import FooIFC
from package import Foo
if isinstance(FooIFC.getinstance(), Foo):
print "Foo"
else:
print "FooBar"
In Jython
, you can also try.在Jython
,您也可以尝试。
from package import FooIFC
from package import Foo
if FooIFC.getClass().getSimpleName() == 'Foo':
print "Foo"
else:
print "FooBar"
Sample Code:示例代码:
import java.util.ArrayList as ArrayList
arr = ArrayList()
arr.add(10)
arr.add(20)
print arr
print "Name:", arr.getClass().getName()
print "Simple Name:", arr.getClass().getSimpleName()
if arr.getClass().getName() == 'java.util.ArrayList':
print "This is an ArrayList"
if arr.getClass().getSimpleName() == 'ArrayList':
print "This is an ArrayList"
Output:输出:
> jython check_type.py
[10, 20]
Name: java.util.ArrayList
Simple Name: ArrayList
This is an ArrayList
This is an ArrayList
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.