티스토리 뷰
Class 클래스 <자료형을 모르는 Class 사용 할 때>
로컬 메모리에 객체 없는 경우, 원격 프로그래밍, 객체의 타입을 알 수 없는 경우에 사용
.class 파일(바이트 코드)의 정보를 가져오거나 instance 생성할 수 있는 메서드가 정의 되어있는 것
Class를 동적으로 로드한다.
//Class.forName("클래스 이름"); Class cl = Class.forName("java.lang.String");
Class 이름으로 Class 클래스 가져오기
Class cl = String.class;
생성된 인스턴스에서 Class 클래스 가져오기
// Object 메서드 // .getClass()를 사용하기 위해서는 instance가 있어야 합니다. String str = new String(); Class cl = str.getClass();
동적 로딩
- Runtime 중에 데이터 타입을 binding하는 방법
Reflection
정확한 Class를 몰라도 Class를 찾는 방법
=> JAVA Class file들은 바이트 코드로 컴파일 되어 static과 함께 method영역에 저장되어서
Class이름만 알면 Class 정보를 찾을 수 있다.
Class 클래스를 사용하여 클래스의 정보(생성자,변수,메서드..)을 알 수 있고 인스턴스를 생성하고 매서드를 호출하는 방식의 프로그래밍
ex>
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, InvocationTargetException{
Person person = new Person("paeng");
Class c1 = Class.forName("ch4_4.Person"); //local에 Person Class가 없을 때 사용
//instance 만들기 .newInstance() -> 반환값 Object
Person person1 = (Person)c1.newInstance();
Class c2 = person.getClass();
Person p = (Person)c2.newInstance(); //객체(instance) 만들기
System.out.println(p);
//local에 Person Class가 없을 때 사용
Class[] ParameterTypes = {String.class};
Constructor cons = c1.getConstructor(ParameterTypes);
Object[] initargs = {"gpaeng"};
Person personPaeng = (Person)cons.newInstance(initargs);
System.out.println(personPaeng);
}
}
Constructor
throw
throws
반응형
'Tip and Error > JAVA' 카테고리의 다른 글
Generic (class 자료형을 자유롭게) (0) | 2021.04.23 |
---|---|
JAVA 컴파일 과정 (0) | 2021.04.17 |
toString() & equals() & hashCode() & clone() (0) | 2021.04.16 |
default & static & private (0) | 2021.04.16 |
인터페이스 활용 (interface) (0) | 2021.04.14 |
공지사항
최근에 올라온 글