Java/Java

Java 기본API클래스 #2

백엔드 신입사원( soft 5.10 입사) 2021. 10. 20. 17:13
반응형

깊은 복제를 하려면 Object의 clone()메소드를 재정의해서 참조 객체를 복제하는 코드를 직접 작성해야한다

예시. 깊은 복제

public class ApiMemberCar_DeepClone {  
public String model;  
public ApiMemberCar_DeepClone(String model) {  
this.model = model;  
}  
}
import java.util.Arrays;  
  
public class ApiMember_DeepClone implements Cloneable {  
public String name;  
public int age;  
public int[] scores; // scores와 ApiMemberCar_DeepClone에 model이 깊은복제대상  
public ApiMemberCar_DeepClone model; //  
  
public ApiMember_DeepClone(String name, int age, int[] scores, ApiMemberCar_DeepClone model) {  
this.name = name;  
this.age = age;  
this.scores = scores;  
this.model = model;  
}  
  
@Override  
protected Object clone() throws CloneNotSupportedException{  
// 먼저얕은복사  
ApiMember_DeepClone cloned = (ApiMember_DeepClone) super.clone(); // object의 clone()호출  
//scores를 깊은복제  
cloned.scores = Arrays.copyOf(this.scores, this.scores.length); // clone()메소드의 재정의  
//model 깊은 복제  
cloned.model = new ApiMemberCar_DeepClone(this.model.model);  
// 리턴  
return cloned;  
}  
  
public ApiMember_DeepClone getMember() {  
ApiMember_DeepClone cloned = null;  
try {  
cloned = ( ApiMember_DeepClone ) clone(); // 재정의된 clone()메소드 호출  
} catch (CloneNotSupportedException e) {  
e.printStackTrace();  
}  
return cloned;  
}  
}
public class ApiMember_DeepClone_Example{  
public static void main(String[] args){  
//원본 객체 생성  
ApiMember_DeepClone ori = new ApiMember_DeepClone("길동", 25, new int[] {90,80}, new ApiMemberCar_DeepClone("쌍용"));  
  
//복제 객체를 얻은 후에 참조 객체의 값을 변경  
ApiMember_DeepClone cloned = ori.getMember();  
cloned.scores[0] = 100;  
cloned.model.model = "스타렉스";  
System.out.println("[복제 객체 필드값]");  
System.out.println(cloned.name);  
System.out.println(cloned.age);  
for(int i=0; i<cloned.scores.length; i++){  
System.out.print(cloned.scores[i]);  
System.out.print((i==(cloned.scores.length-1))?"": ", ");  
}  
System.out.println("\n"+cloned.model.model +"\r");  
System.out.println("[원본 객체 필드값]");  
System.out.println(ori.name);  
System.out.println(ori.age);  
for(int i=0; i<ori.scores.length; i++) {  
System.out.print(ori.scores[i]);  
System.out.print((i==(ori.scores.length-1))?"": ", ");  
}  
System.out.println("\n" + ori.model.model);  
}  
}

객체 소멸자(finalize())

#GC = Garbage Collector가비지 컬랙터
GC는 객체를 소멸하기 직전 객체 소멸자 실행
쓰레기 수집기는 객체를 소멸하기 직전에 마지막으로 객체의 소멸자(finalize())를 실행 시킨다
소멸자는 Object의 finalize()메소드를 말하고, 기본적으로 실행 내용이 없다
만약 객체가 소멸되기 전에 마지막으로 사용했던 자원(데이터 연결, 파일 등)을 닫고 싶거나, 중요한
데이터를 저장하고 싶다면 Object finalize()를 재정의 할수 있다.
finalize() 메소드가 실행되면 번호를 출력하게 해서 어떤 객체가 소멸되는지 확인도 가능하다

예시 finalize()

public class ApiFinalizeCounter {  
private int no;  
public ApiFinalizeCounter(int no) {  
this.no = no;  
}  
  
@Override  
protected void finalize() throws Throwable{  
System.out.println(no + "번 객체의 finalize()가 실행됨");  
}  
}

public class ApiFinalize_Example {  
public static void main(String [] args) {  
ApiFinalizeCounter counter = null;  
for(int i=0; i<=50; i++) {  
counter = new ApiFinalizeCounter(i);  
counter = null; // 객체를 쓰래기로 만들고  
System.gc(); // 쓰레기 수집기 실행시킨다.  
}  
}  
}

Objects 클래스

object의 유틸리티 클래스를 모아둔것 해당 클래스는 객체 비교, 해시코드 생성 , null 여부, 객체 문자열 리턴 등의 연산을 수행하는 정적 메소드들로 구성된 Object의 유틸리티 클래스이다.

예시. 객체 비교(compare(T a, T b, Comparatorc))

import java.util.Comparator;  
import java.util.Objects;  
public class ApiCompareExample {  
public static void main(String[] args) {  
Student s1 = new Student(1);  
Student s2 = new Student(1);  
Student s3 = new Student(2);  
  
int result = Objects.compare(s1, s2, new StudentComparator()); // 비교  
System.out.println(result);  
result = Objects.compare(s1, s3, new StudentComparator());  
System.out.println(result);  
  
}  
static class Student{  
int sno;  
Student(int sno){  
this.sno = sno;  
}  
}  
static class StudentComparator implements Comparator<Student>{  
@Override  
public int compare(Student a, Student b) {  
return Integer.compare(a.sno, b.sno);  
}  
}  
}

그외에도 동등 비교(equals(), deepEquals()), 해시코드 생성(hash(), hashCode()), 널 여부 조사(isNull(), nonNull(), requireNonNull()), 객체 문자정보(toString()) 등이 있다.

System 클래스

자바 프로그램은 운영체제상에서 바로 실행되는 것이 아니라 JVM(자바 가상 머신) 위에서 실행된다. 따라서 운영체제의 모든 기능을 자바 코드로 직접 접근하기는 어렵다. 하지만 java.lang 패키지에 속하는 System클래스를 이용하면 운영체제의 일부 기능은 이용할순 있다.

프로그램 종료(exit())

JVM을 종료 시킬때 System.exit(0); exit메소드로 종료시킬수있다.

해당 메소드는 int 매개값을 지정하도록 되어있는데 일반적으로 정상 종료일 경우 0으로 지정한다. 만일 비정상 종료일 경우 0 이외에 다른 값을 준다.

예시. 상태값이 5일경우 출력을 멈추고 종료시키는 exit 메소드

public class ExitExample{  
public static void main(String[] args){  
// 보안 관리자 설정  
System.setSecurityManager**(**new SecurityManager(){  
@Override  
public void checkExit(int status){  
if(status !=5){  
throw new SecurityException();  
}  
}  
}); // 하나의 실행자로 세미콜론  
  
for(int i=0; i<10; i++){  
// i 값 출력  
system.out.println(i);  
try{  
// jvm 종료요청  
System.exit(i);  
} catch(SecurityException e){  
}  
}  
  
}  
}

쓰래기 수집기gc() (Garbage Collector)

메모리가 부족할 때오 cpu가 한가할 때에 쓰레기 수집기를 실행 시켜 사용하지 않는 객체를 자동으로 제거 한다

쓰레기 수집기는 개발자가 직접 코드로 실행시킬순없고 , jvm에게 가능한 빨리 실행해 달라고 요청할 수는 있다 이것이 system.gc()메소드이다 호출되면 쓰레기 수집기가 바로 실행되는것은 아니고 jvm은 빠른 시간 내에 실행시키기 위해 노력하는것임.

예시.

public class ApiEmployee {  
public int eno;  
public ApiEmployee(int eno) {  
this.eno = eno;  
System.out.println(eno + " 가 메모리에 생성됨");  
}  
  
public void finalize() { // 소멸자  
System.out.println(eno + " 가 메모리에서 제거됨");  
}  
}  
public class ApiEmployeeGC_Example {  
  
public static void main(String[] args) {  
ApiEmployee emp;  
  
emp = new ApiEmployee(1);  
emp = null;  
emp = new ApiEmployee(2);  
emp = new ApiEmployee(3);  
  
System.out.println("emp가 최종적으로 참조하는 번호: " + emp.eno);  
System.gc();  
}  
  
}

현재시각 읽기(currentTimeMillis(), nanoTime()) , 시스템 프로퍼티 읽기(getProperty())

현재 시간을 읽을수있는 밀리 세컨드, 나노단위의 나노세컨드가 도 있다.

public class SystemTimeExample {  
  
public static void main(String[] args) {  
long time1 = System.nanoTime(); // 시작 시간 읽기  
  
int sum = 0;  
for(int i=1; i<=100000; i++) {  
sum += i;  
}  
long time2 = System.nanoTime(); // 끝 시간 읽기  
  
System.out.println(sum);  
System.out.println("합친 계산에 " +(time2-time1) + " 나노초가 소요됨");  
}  
  
}

시스템 프로퍼티.

예시.

public class ApiGetPropertyExample {  
  
public static void main(String[] args) {  
String osName = System.getProperty("os.name"); // 개별속성을 불러온당  
String userName = System.getProperty("user.name");  
String userHome = System.getProperty("user.home");  
  
System.out.println("운영체제: " + osName); // 읽는다.  
System.out.println("사용자: " + userName);  
System.out.println("홈디렉토리: " + userHome);  
  
}  
  
}

class 클래스 (getClass(), forName())

객체 얻기위해서는 Object 클래스가 가지고 있는 getClass () 메소드를 이용하면된다.

Object는 모든 클래스의 최상위 클래스 이므로 모든 클래스에서 getClass() 메소드를 호출할수있다,

예시. 간단한. getClass, forName

public class ApiClassExample {  
  
public static void main(String[] args) {  
  
ApicarClassExample car = new ApicarClassExample();  
Class clazz1 = car.getClass();  
System.out.println(clazz1.getName());  
System.out.println(clazz1.getSimpleName());  
System.out.println(clazz1.getPackage().getName());  
System.out.println();  
  
try {  
Class clazz2 = Class.forName("O020.ApicarClassExample"); // 얻으려는 객체 경로  
System.out.println(clazz2.getName());  
System.out.println(clazz2.getSimpleName());  
System.out.println(clazz2.getPackage().getName());  
  
}catch(ClassNotFoundException e){  
e.printStackTrace();  
}  
}  
  
}

리플렉션 클래스의 생성자 필드 메소드 정보를 알아내는것.

public class Car {  
private String model;  
public String owner;  
  
public Car() {  
}  
  
public Car(String model) {  
this.model = model;  
}  
  
public void setModel(String model) {  
this.model = model;  
}  
  
public String getModel() {  
return model;  
}  
  
private void setOwner(String owner) {  
this.owner = owner;  
}  
  
public String getOwner() {  
return owner;  
}  
}
import java.lang.reflect.*;  
  
public class ReflectionExample {  
public static void main(String[] args) throws Exception {  
Class clazz = Class.forName("code.chap11.src.sec06.exam02_reflection.Car"); // 알아내려는 java파일 경로  
  
System.out.println("[클래스 이름]");  
System.out.println(clazz.getName());  
System.out.println();  
  
System.out.println("[생성자 정보]");  
Constructor[] constructors = clazz.getDeclaredConstructors();  
for(Constructor constructor : constructors) {  
System.out.print(constructor.getName() + "(");  
class[] parameters = constructor.getParameterTypes();  
printParameters(parameters);  
System.out.println(")");  
}  
System.out.println();  
  
System.out.println("[필드 정보]");  
Field[] fields = clazz.getDeclaredFields();  
for(Field field : fields) {  
System.out.println(field.getType().getSimpleName() + " " + field.getName());  
}  
System.out.println();  
  
System.out.println("[메소드 정보]");  
Method[] methods = clazz.getDeclaredMethods();  
for(Method method : methods) {  
System.out.print(method.getName() + "(");  
Class[] parameters = method.getParameterTypes();  
printParameters(parameters);  
System.out.println(")");  
}  
}

Arrays 클래스

배열 조작 기능을가지고있는 클래스 배열 복사 항목 정렬 항목검색등등
# copyOf , copyOfRange , arraycopy , Arrays.sort(배열)로 먼저 정렬 0123순 , Comparable<> compareTo() 등등

copyOf (원본배열, 복사할길이) , copyOfRange(원본배열, 시작인덱스, 끝인덱스)

반응형