java 获取 类名,如何在Java中获取当前的类名,包括包名?

I'm working on a project and one requirement is if the 2nd argument for the main method starts with “/” (for linux) it should consider it as an absolute path (not a problem), but if it doesn't start with “/”, it should get the current working path of the class and append to it the given argument.

I can get the class name in several ways: System.getProperty("java.class.path"), new File(".") and getCanonicalPath(), and so on...

The problem is, this only gives me the directory in which the packages are stored - i.e. if I have a class stored in ".../project/this/is/package/name", it would only give me "/project/" and ignores the package name where the actual .class files lives.

Any suggestions?

EDIT:

Here's the explanation, taken from the exercise description

sourcedir can be either absolute (starting with “/”) or relative to where we run the program from

sourcedir is a given argument for the main method. how can I find that path?

解决方案

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值