java中的toString - 在Android中的System.out.println vs log

时间:2013-09-04 12:52:06

标签: java android printing tostring

让我们假设我有以下类定义:

class Test{
    public String toString(){

        return "hello test";
    }

现在从另一个班级我做以下事情:

Test myTest=new Test();
//output of below will be 'hello test'
System.out.println(myTest);

我在Android中寻找相应的东西,所以我可以在对象上做这样的事情:

Log.d("TAG",myTest);  
or even createToast(Context,myTest,Toast.short).show();

我不想要调用对象toString方法,我只想将对象转储到方法中,它知道它需要像system.out.println那样调用toString。

2 个答案:

答案 0 :(得分:2)

因为Log.X只接受一个String作为第二个参数,你最好做一个调用Android记录器的包装器,如:

static class MyLogger{
        public static void d(String tag,Object o){
            if(o==null){
                throw new NullPointerException("The second parameter can not be null");
            }
            Log.d(tag, o.toString());
        }
    }

答案 1 :(得分:0)

将对象添加到字符串将添加其“toString”方法,而无需调用它

Log.d("TAG", "" + myTest);

甚至

createToast(Context, "" + myTest,Toast.short).show();
相关问题