문자열에서 클래스 유형 가져 오기
나는 String
클래스의 이름을 가지고 있습니다 "Ex"
( .class
확장자 없음 ). 다음 Class
과 같이 변수 에 할당하고 싶습니다.
Class cls = (string).class
어떻게 할 수 있습니까?
Class<?> cls = Class.forName(className);
그러나 귀하 className
는 완전한 자격을 갖추어야합니다.com.mycompany.MyClass
String clsName = "Ex"; // use fully qualified name
Class cls = Class.forName(clsName);
Object clsInstance = (Object) cls.newInstance();
자세한 내용 은 Reflection에 대한 Java Tutorial 추적 ( http://java.sun.com/docs/books/tutorial/reflect/TOC.html) 을 확인하십시오.
다음 forName
방법을 사용할 수 있습니다 Class
.
Class cls = Class.forName(clsName);
Object obj = cls.newInstance();
Java Reflection Concept을 통해 런타임 중에 모든 클래스의 클래스 참조를 얻을 수 있습니다.
아래 코드를 확인하십시오. 아래에 설명이 나와 있습니다.
다음은 반환 된 Class를 사용하여 AClass의 인스턴스를 만드는 한 가지 예입니다.
package com.xyzws;
class AClass {
public AClass() {
System.out.println("AClass's Constructor");
}
static {
System.out.println("static block in AClass");
}
}
public class Program {
public static void main(String[] args) {
try {
System.out.println("The first time calls forName:");
Class c = Class.forName("com.xyzws.AClass");
AClass a = (AClass)c.newInstance();
System.out.println("The second time calls forName:");
Class c1 = Class.forName("com.xyzws.AClass");
} catch (ClassNotFoundException e) {
// ...
} catch (InstantiationException e) {
// ...
} catch (IllegalAccessException e) {
// ...
}
}
}
인쇄 된 출력은
The first time calls forName:
static block in AClass
AClass's Constructor
The second time calls forName:
클래스가 이미로드되었으므로 두 번째 "AClass에 정적 블록"이 없습니다.
설명은 다음과 같습니다.
Class.ForName is called to get a Class Object
By Using the Class Object we are creating the new instance of the Class.
Any doubts about this let me know
eeh.. Class.forName(String classname) ?
Not sure what you are asking, but... Class.forname, maybe?
참고URL : https://stackoverflow.com/questions/2408789/getting-class-type-from-string
'IT박스' 카테고리의 다른 글
Swift (iOS)에서 라디오 버튼과 체크 박스를 만드는 방법은 무엇입니까? (0) | 2020.11.03 |
---|---|
SQL Server : 테이블의 최대 행 수 (0) | 2020.11.03 |
Android Word-Wrap EditText 텍스트 (0) | 2020.11.03 |
PHPStorm / Intellij IDEA를 어둡게 만드는 방법 (단지 색 구성표가 아닌 전체 IDE) (0) | 2020.11.03 |
데코레이터 실행 순서 (0) | 2020.11.02 |