Object created using the "new" keyword and created with reflection

I learned that with Reflection we can create objects without using the "new" keyword. Therefore, I wanted to know if there are differences in them or any specific scenarios for using Reflection. Because so far I have not created or seen any object of creating code with reflection.

Why the use of the "new" has become so used and not reflected.

+3
source share
7 answers

You would use reflection only when you want to create an instance of a type based on its name (string), or a type that you do not have access to at compile time (for example, a plugin). You will not want to use it instead newto create types in normal conditions.

+9
source

Why use of the “new” has become so useful and no reflection.

Compared to the keyword “new”, using reflection is a lot of work; this also leads to less readable code.

Reflection is used when, for one reason or another, the code that creates the instance of the object cannot know the specific type of this object. Reflection is widely used in creation design templates .

+3

, . (, ), , .

+2

. , - , . , , , , . .

, , .

+1

, MyObject , String. new:

MyObject myObject = new MyObject("constructor-arg1");

:

Constructor constructor = MyObject.class.getConstructor(String.class);

MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");

( http://tutorials.jenkov.com/java-reflection/constructors.html)

, , . , . , , .

, , ...

+1

new:

  • , .
  • , .
  • .
  • - # 3 IDE (, Eclipse) .

:

  • , , .

, , new - , 99% . , , (SPI). , .

, , , , , : objenesis .

+1

spring. xml, , . , . , BRMS, - . , , , - , - JDBC (Class.forName( " " )).

0

Source: https://habr.com/ru/post/1729265/


All Articles