java返回Ljava的字符串值。lang.对象
我有以下代码
TreePath tp = jTree.getSelectionPath();
String path = tp.getPath().toString();
这将把路径设置为Ljava.lang.Object;@33530691
,我理解这是因为
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' +Integer.toHexString(hashCode())
但是,如何将这个值作为字符串来获取呢
# 1 楼答案
我不太明白你的问题。这不是已经在你发布的报价中得到了回答吗
getClass().getName() + '@' +Integer.toHexString(hashCode())
是toString()
方法的默认实现,但是如果需要更好的表示,可以重写它(请记住,在您的情况下需要扩展TreePath
)编辑:我想,我现在明白了:
因为
TreePath.getPath()
返回一个对象数组,所以在输出中得到java.lang.Object
# 2 楼答案
若你们想得到一个逗号分隔的字符串,你们可以这样做
String path=new ArrayList(tp.getPath())。toString()
# 3 楼答案
String的
toString()
方法是通过defalut重载的,因此问题不在于字符串路径,而是尝试查看TreePath tp.
我想你需要看看
tp
# 4 楼答案
作为树组件的对象需要重写其toString()方法。你可以用你想要返回的任何东西覆盖它。我假定您正在向树中添加一个自定义对象,因此您可以控制该对象及其toString()方法
# 5 楼答案
getPath()返回表示树中组件的字符串值数组。如果需要根的字符串表示,可以执行getPath()[0]
# 6 楼答案
试试这样: