>  기사  >  Java  >  자바 newInstance()

자바 newInstance()

WBOY
WBOY원래의
2024-08-30 15:35:12670검색

클래스가 새 인스턴스를 동적으로 생성해야 할 때마다 클래스의 Java newinstance() 메서드가 등장합니다. 이 메서드는 클래스를 동적으로 로드하는 데 사용되는 .class 이름인 기존 메서드 위에 호출됩니다. 이 newInstance() 메서드는 객체를 동적으로 생성하기 위해 해당 클래스에 추가로 호출됩니다. 클래스의 이 newInstance() 메서드는 클래스의 매개 변수나 인수를 고려하지 않습니다. 즉, 생성자가 없음을 의미합니다. 따라서 한 클래스에 대해 인수가 없는 생성자라고 부를 수 있습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

public Tsk newInstance() throws InitiationException, IllegalAccessException

구문 흐름은 다음을 나타내는 다음 매개변수로 구성됩니다.

  • 공개: 정의 및 선언되는 클래스에 대한 액세스 한정자
  • : 선언된 클래스 이름이며 제네릭이므로 Object 클래스 및 제네릭처럼 생각할 수 있습니다.
  • newInstance(): 클래스의 .class 이름에 추가하여 동적으로 객체를 생성하고 로드하기 위해 호출되는 메서드의 이름입니다.
  • throws: 예외를 포착하고 발생시키는 키워드입니다.
  • InitiationException: 뒤에 throws 키워드가 있으며 처음에 시작되는 예외를 잡는 데 사용됩니다.
  • IllegalAccessException: 모든 불법적이거나 사용되지 않은 예외를 포착하고 액세스하는 데 사용됩니다.

Java에서 newInstance() 메소드는 어떻게 작동하나요?

클래스 또는 생성자의 newInstance()가 모두 호출되어 클래스의 새 인스턴스를 만드는 데 사용됩니다. 클래스의 newInstance() 메서드를 사용하는 것보다 생성자의 newInstance() 메서드를 사용하는 것이 항상 선호됩니다. 왜냐하면 생성자의 newInstance() 메서드는 newInstance(의 경우가 아닌 여러 인수를 사용할 수 있기 때문입니다. ) 클래스의 newInstance() 메서드는 인수가 없으므로 클래스에 인수가 없는 생성자를 의미합니다. 또한 어떤 클래스의 새로운 오퍼레이터와 비교되어 혼합되기도 합니다.

newInstance() 메서드의 작업 흐름은 이러한 방식으로 새 연산자를 사용하여 객체를 생성한 다음 런타임이나 컴파일 타임에 객체를 생성해야 하는지 아니면 객체를 동적으로 생성하는 데 매우 필요합니다. 런타임에 객체를 생성해야 한다고 결정되면 새 Operator 생성이 모호해집니다. 따라서 런타임에 객체를 생성하고 객체를 동적으로 로드하려면 newInstance() 메소드를 생성하여 활용해야 합니다.

논의한 대로 클래스의 newInstance() 메서드는 먼저 클래스 유형의 객체를 생성한 다음 .class 이름을 사용하여 호출되어 새 인스턴스를 생성합니다. Class.forName() 메소드는 클래스에 대한 객체를 반환하고, 이는 인수로 전달된 해당 클래스의 객체를 반환하며, 매개변수를 전달하는 클래스가 존재하지 않으면 ClassNotFoundException 예외가 발생합니다.

인스턴스화 예외 다음에 throw가 발생하면 메서드가 내부적으로 해당 클래스의 기본 생성자를 호출할 때 호출되어 사용됩니다. 정의되고 지정된 클래스에 대한 접근성이 없으면 IllegalAccessException이 발생합니다. 따라서 동적 로딩을 사용하여 객체의 newInstance() 생성에 제공되는 유연성과 다양성 때문에 클래스의 newInstance() 메서드를 사용하는 것이 좋습니다. 생성자와 개체의 일반적인 동작과 호출은 다르며 메서드와 개체에 전달할 매개변수가 포함되어 있지 않기 때문에 향상됩니다.

Java newInstance()의 예

아래에 언급된 예는 다음과 같습니다.

예시 #1

이 프로그램은 개체를 생성하기 위한 newInstance 메서드와 함께 Class.forName 메서드를 설명한 다음 해당 클래스의 개체를 인쇄하여 동물의 값을 인쇄하고 예외를 생성하는 데 사용됩니다.

코드:

class Animal {  int p; }
class Birds {  int q; }
public class NewInstanceTst
{
public static void sounds(String s)  throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
Object obj_1 = Class.forName(s).newInstance();
System.out.println("Creation of newly instantiated class:"
+ obj_1.getClass().getName());
}
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
sounds("Animal");
}
}

출력:

자바 newInstance()

예시 #2

이 프로그램은 매개변수 또는 생성자를 전달하는 Java의 newInstance 클래스를 보여줍니다. 그런 다음 객체의 동적 할당에 사용되지만 잘못된 예외가 발생하므로 사용되지 않습니다. 인스턴스화된 클래스가 객체의 동적 로딩을 처리할 수 있는지 확인하기 위해 테스트 클래스를 작성하고 실행합니다.

코드:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class NwInstncWithconstructors {
public static void main(String[] args)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Constructor[] constructor_a  = Instnace_Constructor_Test.class.getConstructors();
Instnace_Constructor_Test animal = (Instnace_Constructor_Test)constructor_a[0].newInstance();
System.out.println(animal.content);
}
}
class Instnace_Constructor_Test {
String content;
public Instnace_Constructor_Test()
{
System.out.println("Create a new Instance:");
content = "new_instance_of_the_value";
}
}

Output:

자바 newInstance()

Example #3

This program also demonstrates the newInstance class of Java. Still, without passing parameters or constructors, it is used for the dynamic allocation of objects seamlessly and makes the overall class flexible for allocation. Still, if not used, it will throw illegal exceptions. A test class is written and executed to verify whether the instantiated class can handle the object’s dynamic loading. This program calls for a no-arg method which means newInstance class directly.

Code:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class NewInstanceWithout_Constructors {
public static void main(String[] args)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Constructor[] constructor_without_arr = Without_constructor_Test.class.getConstructors();
Without_constructor_Test sm_ob
= (Without_constructor_Test)constructor_without_arr[0]
.newInstance("one_field_value");
System.out.println(sm_ob.getthat_value());
}
}
class Without_constructor_Test {
private String that_value;
public Without_constructor_Test(String that_value)
{
this.that_value = that_value;
}
public String getthat_value()
{
return that_value;
}
public void setthat_value(String that_value)
{
this.that_value = that_value;
}
}

Output:

자바 newInstance()

Note: It is always recommended to use a newInstance class instead of using a newInstance constructor because it can easily perform dynamic loading of the class and is flexible, unlike the newInstance constructor, which is not at all preferable if used with multiple parameters that too at the run time.

Conclusion

newInstance() method of java class is an added advantage as it is used to dynamically load the object without passing multiple parameters, and then it can be used with versatility within the class, and no external method is called at the run time with the help of .classForName method of the class the work gets solved relentlessly.

위 내용은 자바 newInstance()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Java의 가상 함수다음 기사:Java의 가상 함수