this.taste = taste;
}
}
Apple 类包含 :
5 个属性:private static int count;
private final int id = count++;
String color;
private int size;
public float price;
4 个构造方法:public Apple()
public Apple(String color, int size)
private Apple(String color, Float price)
Apple(String color)
1个静态方法:public static int getCount()
7个成员方法:public String getColor()
public int getSize()
public void setSize(int size)
public float getPrice()
private void checkPrice(float price)
void checkSize(Integer size)
public boolean initColorAndPrice(String color, float price)
Fruit 类包括:
1个属性:public String taste;
1个构造方法:public Fruit()
2个成员方法:public String getTaste()
public void setTaste(String taste)
2.1 构造函数构造函数
2.1.1 获取构造函数获取构造函数
在 Class 类中提供了 4 种相应的 API 可以用来获取构造函数的 Constructor 对象:
public Constructor getConstructor(Class... parameterTypes) throws NoSuchMethodException, SecurityException :返回与指定的 parameterTypes 相
匹配的公共公共构造方法的 Constructor 对象;
public Constructor[] getConstructors() throws SecurityException:返回此类公共公共构造方法的 Constructor 对象数组;
public Constructor getDeclaredConstructor(Class... parameterTypes) throws NoSuchMethodException, SecurityException :带有指定参数列表的构
造方法的 Constructor 对象;
public Constructor[] getDeclaredConstructors() throws SecurityException:返回此类所有所有已声明的构造方法的 Constructor 对象的数组。
在进行代码演示之前,我们先观察一下上面的 4 个 API:
1 和 2 都是只能获取公共的构造方法对象;
3 和 4 是可以获取所有(public,proctected,private 等)符合的构造方法对象,它们的函数名都包含了 Declared;
1 和 3 都是可以传入参数列表,返回单个的构造方法对象,还有可以抛出NoSuchMethodException;
2 和 4 都不需要传参数,返回一个构造方法对象的数组。
下面是演示代码:
package com.java.advanced.features.reflect.classinternalinfo.constructor;
import com.java.advanced.features.reflect.Apple;
import java.lang.reflect.Constructor;
public class ConstructorGetTest {
public static void main(String[] args) {
Class appleClass = Apple.class;
System.out.println("1, 演示 public Constructor[] getConstructors()");
System.out.println("获取所有的公共构造方法对象数组:");
Constructor[] constructors = appleClass.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("2, 演示 public Constructor getConstructor(Class... parameterTypes)");
评论0
最新资源