Java中的构造函数 isSynthetic() 方法及示例
Java.lang.reflect.Constructor 类的isSynthetic()方法用于返回布尔值 true,如果此构造器对象是合成构造,否则方法返回 false,表明此构造不是合成构造。正如我们所知,合成构造是由Java编译器为内部目的而创建的类、字段和方法。在 Constructor 的情况下,合成构造是由Java编译器创建的供内部使用的构造函数。此方法有助于识别这些构造。
句法:
public boolean isSynthetic()
参数:此方法不接受任何内容。
返回:当且仅当此可执行文件是Java语言规范定义的合成构造时,此方法才返回 true。
下面的程序说明了 isSynthetic() 方法:
方案一:
// Java program to illustrate isSynthetic() method
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String[] args)
{
// create a class object
Class classObj = shape.class;
// get Constructor object
// array from class object
Constructor[] cons = classObj.getConstructors();
// check isSynthetic or not
boolean answer = cons[0].isSynthetic();
// print result
System.out.println("isSynthetic : " + answer);
}
@CustomAnnotation(createValues = "GFG")
public class shape {
@CustomAnnotation(createValues = "GFG")
public shape()
{
}
}
// create a custom annotation
public @interface CustomAnnotation {
public String createValues();
}
}
isSynthetic : false
方案二:
// Java program to illustrate isSynthetic() method
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String[] args)
{
// create a class object
Class classObj = String.class;
// get Constructor object
// array from class object
Constructor[] cons = classObj.getConstructors();
for (int i = 0; i < cons.length; i++) {
System.out.println("Constructor: "
+ cons[i]);
// get array of isSynthetic
boolean answer = cons[0].isSynthetic();
// print result
System.out.println("isSynthetic : " + answer);
}
}
}
Constructor: public java.lang.String(byte[], int, int)
isSynthetic : false
Constructor: public java.lang.String(byte[], java.nio.charset.Charset)
isSynthetic : false
Constructor: public java.lang.String(byte[], java.lang.String) throws java.io.UnsupportedEncodingException
isSynthetic : false
Constructor: public java.lang.String(byte[], int, int, java.nio.charset.Charset)
isSynthetic : false
Constructor: public java.lang.String(byte[], int, int, java.lang.String) throws java.io.UnsupportedEncodingException
isSynthetic : false
Constructor: public java.lang.String(java.lang.StringBuilder)
isSynthetic : false
Constructor: public java.lang.String(java.lang.StringBuffer)
isSynthetic : false
Constructor: public java.lang.String(byte[])
isSynthetic : false
Constructor: public java.lang.String(int[], int, int)
isSynthetic : false
Constructor: public java.lang.String()
isSynthetic : false
Constructor: public java.lang.String(char[])
isSynthetic : false
Constructor: public java.lang.String(java.lang.String)
isSynthetic : false
Constructor: public java.lang.String(char[], int, int)
isSynthetic : false
Constructor: public java.lang.String(byte[], int)
isSynthetic : false
Constructor: public java.lang.String(byte[], int, int, int)
isSynthetic : false
参考资料: https: Java()