this.getClass()得到什么? 

this 表示当前对象的引用; 

getClass() 是 java.lang.Object 中的方法,它返回一个对象的运行时类; 
this.getClass() 就是返回当前对象的运行时类。 

 

Logger.getLogger(this.getClass())又得到什么? 
他得到一个Logger对象,这个Logger将监视this.getClass()这个运行时类,这个运行时类里面你可能创建了log.info(""), log.debug(""),……等语句,那么这些语句就会根据你预先定义的Logger级别来输出你的日志。就跟你写System.out.print("")一样,不同的是Logger可以根据需要按级别进行日志输出控制。(当然这只是一方面) 

 

Logger.getLogger(this.getClass())这样写,有什么好处? 
这样一来你只需要在基类中写一行代码就可以了,子类可以直接使用,这也是复用的原则。

 

  • package com.zhaipuhong.j2se.keywords;  
  •   
  • public class ThisKeywordsA {  
  •     protected String className = this.getClass().toString();  
  •       
  •     public ThisKeywordsA(){  
  •         System.out.println("ThisKeywordsA className == " + className);  
  •     }  
  • }  
  •   
  • package com.zhaipuhong.j2se.keywords;  
  •   
  • public class ThisKeywordsB extends ThisKeywordsA{  
  •       
  •     public ThisKeywordsB(){  
  •         System.out.println("ThisKeywordsB className == " + className);  
  •     }  
  •     /** 
  •      * @param args 
  •      */  
  •     public static void main(String[] args) {  
  •         // TODO Auto-generated method stub  
  •         ThisKeywordsB b = new ThisKeywordsB();  
  •     }  
  •   
  • }  

  • 运行结果: 
    ThisKeywordsA className == class com.zhaipuhong.j2se.keywords.ThisKeywordsB 
    ThisKeywordsB className == class com.zhaipuhong.j2se.keywords.ThisKeywordsB 

    由于B继承A,A对象首先被创建(请不要考虑抽象类和接口^_^)然后作为B对象的字对象创建B 对象. 此时的Logger就是B对象的一部分,可以为B对象所用。 

    this指的是子类的对象

    相关文章:

    • 2022-01-03
    • 2021-06-16
    • 2022-12-23
    • 2022-12-23
    • 2022-12-23
    • 2022-12-23
    • 2021-12-19
    • 2022-12-23
    猜你喜欢
    • 2021-07-24
    • 2021-08-20
    • 2021-10-09
    • 2022-12-23
    • 2022-12-23
    • 2022-12-23
    相关资源
    相似解决方案