檢查對象是否來自某個包

[英]Check if object is from certain package


Is there a way to check if an object's class is from a certain package?

有沒有辦法檢查對象的類是否來自某個包?

Like, when I check if an object is of a certain class using instanceof, I want something similar to check for a package in Java.

就像,當我使用instanceof檢查某個對象是否屬於某個類時,我想要類似的東西來檢查Java中的包。

3 个解决方案

#1


11  

You can check using

你可以查看使用

myInstance.getClass().getPackage()

#2


7  

if (instanceofClass.getClass().getPackage().getName().equals("packageyouwanttocheck")) {
    // your code
}

#3


1  

Here's an example on how you can do that.

這是一個如何做到這一點的例子。

package my.packaging.name;

class X {
}

public class Main { 
    public static void main(String[] args) {
        String packageName = "my.packaging.name";
        X x = new X();
        if (x.getClass().getPackage().getName().equals(packageName)) {
            System.out.println("x belongs to package my.packaging.name");
        } else {
            System.out.println("x does not belong to package my.packaging.name");
        }
    }
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/02/21/72a28816351c1caa51e89f041c8cd181.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com