如何找到给定类名的包名? [英] How to find the package name given a class name?

查看:245
本文介绍了如何找到给定类名的包名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定类名作为字符串,如何在运行时获取它的包名称?我没有完全限定名称与包名称+类名称。只需要类名。

Given a class name as a string, how do I get the package name of it at run time ? I do not have the fully qualified name with package name + class name. Simply only the class name.

我想要在 Class.forName()方法中使用包名。

I want the package name to be used in Class.forName() method.

我找到第一个匹配的软件包名称(如果多个软件包具有相同的类)是完全正确的。

I am perfectly fine with finding the first matching package name (if multiple packages have the same class).

任何想法?

UPDATE

我没有类实例可以工作。我的要求是使用 Class.forName()方法创建一个类。但我只是有类名作为字符串。我需要一些方法来循环通过包,并确定类是否属于包。

I DO NOT have a Class instance to work on. My requirement is to create a Class using the Class.forName() method. But I simply have ONLY the class name as a string. I need some way to loop though the packages and identify if the class I have belongs to the package.

异常的堆栈跟踪是

Exception in thread "main" java.lang.ClassNotFoundException: MyAddressBookPage
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)


推荐答案

这很可能是一个令人难以置信的低效,,肿,不方便的方式来做你想达到的目标,希望已经有一个out-of -box,单一方法来做...但它应该工作。

This is most likely an incredibly inefficient, bloated, inconvenient way of doing what you're trying to achieve, and hopefully there's already an out-of-the-box, single way to do it... but it should work.

基本上,扫描类路径中的每个类,直到找到一个类 getSimpleName()匹配您拥有的类名。

Basically, scan through every class in the class path, until you find a class where getSimpleName() matches the class name you have.

我建议您查看 Google Classpath Explorer ,以帮助管理这样做的基本要素。

I recommend looking at Google Classpath Explorer to help manage the nuts and bolts of doing this.

像这样:

 ClassPath classpath = new ClassPathFactory().createFromJVM();
 RegExpResourceFilter regExpResourceFilter = new RegExpResourceFilter(".*", ".*\\.class");
 String[] resources = classpath.findResources("", regExpResourceFilter);

resources com / foo / bar / Baz.class'。你现在可以简单地循环并找到匹配的条目,并将它们从斜线转换为点线,剥离'.class'等。只需要小心尝试匹配内部类,因为它们将有一个'$'字符。

resources is an array of Strings like 'com/foo/bar/Baz.class'. You can now simply loop through and find matching entries, and transform them from slashed to dotted, strip out '.class', etc. Just be careful around trying to match inner classes, as they will have a '$' character in them.

此外,据我所知,这将导致这些类加载。

Also, as far as I am aware, this will NOT cause those classes to be loaded.

这篇关于如何找到给定类名的包名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆