Java newInstance()

WBOY
リリース: 2024-08-30 15:35:12
オリジナル
670 人が閲覧しました

クラスが新しいインスタンスを動的に作成する必要がある場合は常に、クラスの Java newinstance() メソッドが登場します。このメソッドは、既存のメソッドの上に呼び出されます。これは、クラスを動的にロードするために使用される .class 名です。この newInstance() メソッドは、オブジェクトを動的に作成するためにそのクラスに加えて呼び出されます。クラスのこの newInstance () メソッドは、クラスからのパラメーターや引数を考慮しません。これは、コンストラクターを持たないことを意味します。したがって、これは 1 つのクラスの引数なしのコンストラクターと呼ぶことができます。

広告 このカテゴリーの人気コース JAVA マスタリー - スペシャライゼーション | 78 コース シリーズ | 15 回の模擬テスト

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

構文

public Tsk newInstance() throws InitiationException, IllegalAccessException
ログイン後にコピー

構文フローは、次のことを表す次のパラメーターで構成されます。

  • パブリック: 定義および宣言されるクラスのアクセス修飾子。
  • Tsk: 宣言されたクラスの名前であり、ジェネリックです。つまり、オブジェクト クラスおよびジェネリックと同様に考えることができます。
  • newInstance(): クラスの .class 名に加えてオブジェクトを動的に作成およびロードするために呼び出されるメソッドの名前。
  • throws: 例外をキャッチしてスローするためのキーワード。
  • InitiationException: の後に throws キーワードが続き、最初に開始される例外をキャッチするために使用されます。
  • IllegalAccessException: すべての違法または未使用の例外をキャッチしてアクセスするために使用されます。

Java では newInstance() メソッドはどのように機能しますか?

クラスの newInstance() またはコンストラクターの両方が呼び出され、クラスの新しいインスタンスを作成するために使用されます。コンストラクターの newInstance() メソッドは任意の数の引数を使用できるが、 newInstance( ) クラスの newInstance() メソッドと同様に、クラスのメソッドは引数を持たず、これはクラス内の引数なしのコンストラクターを意味します。また、場合によっては、任意のクラスの新しいオペレーターと比較され、ブレンドされることもあります。

newInstance() メソッドのワークフローは、このようにして、オブジェクトの作成に新しい Operator が使用され、実行時またはコンパイル時にオブジェクトを作成する必要があるかどうかが決定されます。オブジェクトを動的に作成するために非常に必要です。実行時にオブジェクトを作成する必要があると判断された場合、新しい Operator の作成は曖昧になります。したがって、実行時にオブジェクトを作成し、オブジェクトを動的にロードするには、newInstance() メソッドを作成して使用する必要があります。

前述したように、クラスの newInstance() メソッドは、最初にクラス型のオブジェクトを作成し、次に .class 名を使用して呼び出され、新しいインスタンスを作成します。 Class.forName() メソッドは、そのクラスのオブジェクトを返します。このメソッドは、引数として渡されたそのクラスのオブジェクトを返します。パラメータを渡すクラスが存在しない場合は、ClassNotFoundException の例外をスローします。

メソッドがそのクラスのデフォルトのコンストラクターを内部的に呼び出すときに、スローが続くインスタンス化例外が呼び出され、使用されます。定義および指定されたクラスにアクセスできない場合、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");
}
}
ログイン後にコピー

出力:

Java 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:

Java 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:

Java 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.

以上がJava newInstance()の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!