Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมื่อใดควรใช้คลาส ServiceLoader ในโมดูลใน Java 9


Java มี ServiceLoader คลาสจาก java.util แพ็คเกจที่สามารถช่วยในการ ค้นหา ผู้ให้บริการ ที่รันไทม์โดยการค้นหาใน classpath สำหรับผู้ให้บริการที่กำหนดไว้ในโมดูล เราสามารถดูตัวอย่างแอปพลิเคชันเพื่อประกาศโมดูลพร้อมบริการและวิธีการทำงาน

ตัวอย่างเช่น เรามี "test.app " โมดูลที่เราต้องใช้ Logger ที่สามารถดึงข้อมูลจาก System.getLogger() วิธีการจากโรงงานด้วยความช่วยเหลือของ LoggerFinder บริการ

module com.tutorialspoint.test.app {
   requires java.logging;
   exports com.tutorialspoint.platformlogging.app;
   uses java.lang.System.LoggerFinder;
}

ด้านล่างคือ test.app.MainApp คลาส:

package com.tutorialspoint.platformlogging.app;

public class MainApp {
   private static Logger LOGGER = System.getLogger();
   public static void main(String args[]) {
      LOGGER.log();
   }
}


นี่คือ LoggerFinder การใช้งานภายใน "ทดสอบ .logging " โมดูล:

package com.tutorialspoint.platformlogging.logger;

public class MyLoggerFinder extends LoggerFinder {
   @Override
   public Logger getLogger(String name, Module module) {
      // return a Logger depending on name/module
   }
}

ใน "test.logging " ประกาศโมดูล เราสามารถจัดเตรียมการใช้งาน LoggerFinder บริการด้วย "ให้ – ด้วย " ประโยค

module com.tutorialspoint.test.logging {
   provides java.lang.System.LoggerFinder
   with com.tutorialspoint.platformlogging.logger.MyLoggerFinder;
}