繁体   English   中英

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

[英]toString in java - System.out.println vs log in Android

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

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。

因为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());
        }
    }

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

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

甚至

createToast(Context, "" + myTest,Toast.short).show();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM