在Java中引用包而不使用字符串

huangapple go评论86阅读模式
英文:

Referencing packages in java without using String

问题

在Java代码中是否有一种方法可以引用一个包而不使用字符串?

让我解释一下:

我有一个函数,它获取包中包含的所有对象,但是我必须使用一个字符串来引用那个包,比如说"com.google.guava"。虽然这样可以工作,但是如果我改变包的名称,IDE无法自动重构引用;或者如果包是外部的,在主要版本更改后消失,编译时也无法检测到。

对于类,如果可能的话,我会直接使用Class对象,或者如果我需要表示类的完全限定类名的字符串,则会使用Class#getName,但我不知道是否有办法在处理包时也这样做。

有时我会这样做:

Class<?> clazz = Foo.class;
Package p = clazz.getPackage();

这只是一种好奇,而不是真正的问题,我通常只是通过字符串引用,并编写一个JUnit测试来检测是否使用了不存在的包。

英文:

Is there a way to reference a package in java in code without using a String?

Let me explain myself:

I've a function that fetches all object contained in a package, but I've to reference that package using a String, lets say "com.google.guava". This works, however, If I change the package name, the IDE is not able to automatically refractor the references, or if the package is external and dissapears after a major version change it is not detected at compile time.

With classes, I'd use a Class object directly when possible or Class#getName if what I need is a String representing the FQDN of the class, but I don't know if there's a way to do so with packages.

Sometimes I just do

Class&lt;?&gt; clazz = Foo.class;
Package p = clazz.getPackage();

This is more a curiosity than a real issue, I usually just reference by String and write a junit test in order to detect nom-existant packages used this way

答案1

得分: 2

我可以想到以下几种获取 Package 对象的方法:

  1. 调用 classLoader.getPackage(java.lang.String) 或者 Package.getPackage(java.lang.String)。这些方法已经被标记为废弃。

  2. 调用 Package classLoader.getDefinedPackage(java.lang.String)

  3. 调用 Package class.getPackage()

  4. 调用 Package[] Package.getPackages(),然后在返回的数组中搜索你想要的那个。

最后两种方法都是使用 String 来查找一个 Package

对于包(packages),没有类似于 Java 中的“类字面量”(例如 SomeClass.class)的等效概念。

英文:

I can think of the following ways to get a Package object:

  1. Call classLoader.getPackage(java.lang.String) or Package.getPackage(java.lang.String). These methods are deprecated.

  2. Call Package classLoader.getDefinedPackage(java.lang.String)

  3. Call Package class.getPackage()

  4. Call Package[] Package.getPackages() and then scan through the resulting array for the one that you want.

The last two approaches qualify as finding a Package with using a String.

There is no equivalent to a Java "class literal" (i.e. SomeClass.class) for packages.

huangapple
  • 本文由 发表于 2020年5月30日 22:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/62103852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定