logo

Java의 마커 인터페이스

이 섹션에서는 다음에 대해 논의하겠습니다. Java의 마커 인터페이스 , 그것은 사용, 내장( 직렬화 가능 , 복제 가능 및 원격 인터페이스) 그리고 맞춤형 마커 인터페이스 예를 들어.

마커 인터페이스란 무엇입니까?

상호 작용 메소드, 필드 및 상수를 포함하지 않는 것을 마커 인터페이스 . 즉, 빈 인터페이스는 다음과 같이 알려져 있습니다. 마커 인터페이스 또는 태그 인터페이스. 개체에 대한 런타임 유형 정보를 전달합니다. 그 이유는 JVM 컴파일러에는 객체에 대한 추가 정보가 있습니다. 그만큼 직렬화 가능 그리고 복제 가능 인터페이스는 마커 인터페이스의 예입니다. 즉, JVM에 대한 신호 또는 명령을 나타냅니다.

마커 인터페이스의 선언은 Java의 인터페이스와 동일하지만 인터페이스는 비어 있어야 합니다. 예를 들어:

 public interface Serializable { } 

마커 인터페이스와 동일한 결과를 생성하는 마커 인터페이스에는 두 가지 대안이 있습니다.

    내부 플래그:특정 작업을 나타내기 위해 마커 인터페이스 대신 사용할 수 있습니다.주석:자바 5부터 마커 인터페이스가 생략되었습니다. . 마커 인터페이스 대신 Java 5는 다음을 제공합니다. 주석 동일한 결과를 얻으려면. 이는 유연한 메타데이터 기능을 허용합니다. 따라서 어떤 클래스에든 주석을 적용하면 특정 작업을 수행할 수 있습니다.

마커 인터페이스의 사용

마커 인터페이스는 이를 구현하는 클래스에 특별한 동작을 추가할 수 있도록 메시지로 Java 컴파일러에 알리는 태그로 사용됩니다. Java 마커 인터페이스는 클래스에 대한 정보가 있고 해당 정보가 절대 변경되지 않는 경우 유용합니다. 이러한 경우 동일한 내용을 나타내기 위해 마커 인터페이스 표현을 사용합니다. 빈 인터페이스를 구현하면 컴파일러에게 몇 가지 작업을 수행하도록 지시합니다.

코드를 논리적으로 구분하는 데 사용되며, 코드를 분류하는 좋은 방법입니다. API 개발 및 Spring과 같은 프레임워크에서 더 유용합니다.

리눅스 만들기

내장 마커 인터페이스

~ 안에 자바 , 내장 마커 인터페이스는 JDK에 이미 존재하며 바로 사용할 수 있는 인터페이스입니다. 내장된 마커 인터페이스는 다양하며 그 중 일부는 다음과 같습니다.

  • 복제 가능한 인터페이스
  • 직렬화 가능 인터페이스
  • 원격 인터페이스

하나씩 자세히 논의해보자.

복제 가능한 인터페이스

청소 가능한 인터페이스 Java에서는 다음에 속하는 마커 인터페이스이기도 합니다. java.lang 패키지. 다른 이름을 가진 객체의 복제본(사본)을 생성합니다. 복제할 클래스 객체의 클래스에 인터페이스를 구현할 수 있습니다. 이는 다음을 나타냅니다. 클론() Object 클래스의 메소드 클래스에서 Cloneable 인터페이스를 구현하지 않고 clone() 메서드를 호출하면 ClassNotSupportedException.

Cloneable 인터페이스를 구현하는 클래스는 공용 메서드로 clone() 메서드를 재정의해야 합니다. 예를 살펴보겠습니다.

제품.java

 import java.util.Scanner; public class Product implements Cloneable { int pid; String pname; double pcost; //Product class constructor public Product (int pid, String pname, double pcost) { this.pid = pid; this.pname = pname; this.pcost = pcost; } //method that prints the detail on the console public void showDetail() { System.out.println('Product ID: '+pid); System.out.println('Product Name: '+pname); System.out.println('Product Cost: '+pcost); } public static void main (String args[]) throws CloneNotSupportedException { //reading values of the product from the user Scanner sc = new Scanner(System.in); System.out.print('Enter product ID: '); int pid = sc.nextInt(); System.out.print('Enter product name: '); String pname = sc.next(); System.out.print('Enter product Cost: '); double pcost = sc.nextDouble(); System.out.println('-------Product Detail--------'); Product p1 = new Product(pid, pname, pcost); //cloning the object of the Product class using the clone() method Product p2 = (Product) p1.clone(); //invoking the method to print detail p2.showDetail(); } } 

산출:

이진 검색 트리]
 Enter product ID: 139872 Enter product name: Printer Enter product Cost: 3459.67 -------Product Detail-------- Product ID: 139872 Product Name: Printer Product Cost: 3459.67 

직렬화 가능 인터페이스

이는 Java에서 정의된 마커 인터페이스입니다. java.io 패키지. 클래스를 직렬화하려면 다음을 구현해야 합니다. 직렬화 가능 상호 작용. 클래스가 직렬화 가능 인터페이스를 구현하는 경우 해당 클래스의 객체 상태를 직렬화하거나 역직렬화할 수 있습니다.

직렬화(객체를 바이트 스트림으로 변환)는 다음과 같은 메커니즘입니다. 객체 상태를 메모리에서 읽어 파일이나 데이터베이스에 기록합니다. . 역직렬화(바이트 스트림을 객체로 변환)는 직렬화의 반대입니다. 파일이나 데이터베이스에서 객체 상태를 읽고 다시 메모리에 기록 객체의 역직렬화라고 합니다.

Java의 마커 인터페이스

직렬화(쓰기)는 다음을 사용하여 수행할 수 있습니다. 객체출력스트림 클래스 및 역직렬화(읽기)는 다음을 사용하여 수행할 수 있습니다. 객체입력스트림 수업.

직렬화 및 역직렬화의 예를 살펴보겠습니다.

직렬화의 예

Employee.java

 import java.io.Serializable; public class Employee implements Serializable { int empid; String empname; public Employee(int empid, String empname) { this.empid = empid; this.empname = empname; } } 

직렬화Example.java

문자열 메소드 자바로
 import java.io.*; class SerializationExample { public static void main(String args[]) { try { //Creating the object Employee emp =new Employee(1187345,'Andrew'); //Creating stream and writing the object FileOutputStream fout=new FileOutputStream('employee data.txt'); ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(emp); out.flush(); //closing the stream out.close(); System.out.println('Data has been read from the file.'); } catch(Exception e) { e.printStackTrace(); } } } 

산출:

 Data has been read from the file. 

역직렬화의 예

객체 상태를 역직렬화해 보겠습니다.

역직렬화Example.java

 import java.io.*; class DeserializationExample { public static void main(String args[]) { try { //Creating stream to read the object ObjectInputStream in=new ObjectInputStream(new FileInputStream('employee data.txt')); Employee emp=(Employee)in.readObject(); //printing the data of the serialized object System.out.println(emp.empid+' '+emp.empname); //closing the stream in.close(); } catch(Exception e) { e.printStackTrace(); } } } 

산출:

 1187345 Andrew 

원격 인터페이스

원격 인터페이스 에 속하는 마커 인터페이스입니다. java.rmi 패키지. 개체를 다른 컴퓨터(호스트)에서 액세스할 수 있는 원격 개체로 표시합니다. 객체를 원격으로 만들려면 Remote 인터페이스를 구현해야 합니다. 이는 로컬이 아닌 JVM에서 해당 메소드를 호출할 수 있는 인터페이스를 식별합니다. 모든 원격 개체는 인터페이스를 직접 또는 간접적으로 구현해야 합니다.

속성 오류 파이썬

원격 인터페이스를 정의하고 이를 Java 프로그램에서 구현해 보겠습니다.

원격 인터페이스 정의

 import java.rmi.*; public interface AddAll extends Remote { public int add(int r, int s)throws RemoteException; } 

원격 인터페이스 구현

원격 인터페이스를 구현하는 방법에는 다음 두 가지가 있습니다.

  • UnicastRemoteObject 클래스를 확장하여
  • UnicastRemoteObject 클래스의 importObject() 메소드를 사용하여

AddAllRemote.java

 import java.rmi.*; import java.rmi.server.*; public class AddAllRemote extends UnicastRemoteObject implements Adder { AddAllRemote()throws RemoteException { super(); } public int add(int r, int s) { return r+s; } 

원격 애플리케이션 생성 및 시작

서버.자바

문자열을 int로 변환하는 변환기
 import java.rmi.*; import java.rmi.registry.*; public class Server { public static void main(String args[]) { try { AddAll stub=new AddAllRemote(); Naming.rebind('rmi://localhost:5000/sak',stub); } catch(Exception e) { System.out.println(e); } } } 

클라이언트 애플리케이션 생성 및 시작

클라이언트.자바

 import java.rmi.*; public class Client { public static void main(String args[]) { try { AddAll stub=(AddAll)Naming.lookup('rmi://localhost:5000/sak'); System.out.println(stub.add(29,18)); } catch(Exception e) { } } } 

맞춤형 마커 인터페이스

내장된 마커 인터페이스 외에도 Java를 사용하면 자체 마커 인터페이스를 만들 수도 있습니다. 예를 살펴보겠습니다.

CustomMarkerInterfaceExample.java

 //custom marker interface interface Car { } //custom marker interface interface Engine { } //class that implements the Car marker interface class Vehicle implements Car { static void isVehicle() { System.out.println('Car is a vehicle.'); } } //class that implements the Engine marker interface class Status implements Engine { static void isWorking() { System.out.println('Yes, engine is working.'); } } //main class public class CustomMarkerInterfaceExample { public static void main(String args[]) { //invoking the methods of the class Vehicle.isVehicle(); Status.isWorking(); } } 

산출:

 Car is a vehicle. Yes, engine is working.