Java Reflection - Constructors
2015-05-31 11:48
363 查看
http://tutorials.jenkov.com/java-reflection/constructors.html
Using Java Reflection you can inspect the constructors of classes and instantiate objects at runtime. This is done via the Java class
about the Java
The
If you know the precise parameter types of the constructor you want to access, you can do so rather than obtain the array all constructors. This example returns the public constructor of the given class which takes a
parameter:
If no constructor matches the given constructor arguments, in this case
The
taking a
Using Java Reflection you can inspect the constructors of classes and instantiate objects at runtime. This is done via the Java class
java.lang.reflect.Constructor. This text will get into more detail
about the Java
Constructorobject.
Obtaining Constructor Objects
TheConstructorclass is obtained from the
Classobject. Here is an example:
Class aClass = ...//obtain class object Constructor[] constructors = aClass.getConstructors();
The
Constructor[]array will have one
Constructorinstance for each public constructor declared in the class.
If you know the precise parameter types of the constructor you want to access, you can do so rather than obtain the array all constructors. This example returns the public constructor of the given class which takes a
Stringas
parameter:
Class aClass = ...//obtain class object Constructor constructor = aClass.getConstructor(new Class[]{String.class});
If no constructor matches the given constructor arguments, in this case
String.class, a
NoSuchMethodExceptionis thrown.
Constructor Parameters
You can read what parameters a given constructor takes like this:Constructor constructor = ... // obtain constructor - see above Class[] parameterTypes = constructor.getParameterTypes();
Instantiating Objects using Constructor Object
You can instantiate an object like this://get constructor that takes a String as argument Constructor constructor = MyObject.class.getConstructor(String.class); MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");
The
Constructor.newInstance()method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the constructor you are invoking. In this case it was a constructor
taking a
String, so one
Stringmust be supplied.
相关文章推荐
- 反射0-Java Reflection Tutorial
- Java 多线程详解
- Java语法错误之-执行不到的代码(Unreachable code)
- java范型的应用
- java中的各种数据类型在内存中存储的方式
- 杭电ACM2019java做法
- 杭电ACM2019java做法
- JAVA -- 线程的sleep()方法为什么是静态的
- JAVA -- 线程的sleep()方法为什么是静态的
- JAVA -- 线程的sleep()方法为什么是静态的
- hdfs查看集群目录报javaIO异常
- OSS实现多文件多线程的断点下载(java)
- Java知多少(78)Java向量(Vector)及其应用
- java null空判断问题
- Vijava 学习笔记 删除虚拟机(delete Virtual Machine)
- 基本类型与包装类的区别
- Java Thread State 分析
- java个人学习笔记:三元
- struts中jsp表单控件命名注意
- Java 虚拟机