构造函数是否生成默认构造函数? [英] Is constructor generated default constructor?

查看:47
本文介绍了构造函数是否生成默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过反射找出构造函数是否是编译器生成的默认构造函数?或者有其他方法吗?

Is there a way to find out by reflection whether a constructor is a compiler generated default constructor or not? Or is there some other way?

令人惊讶的是,isSynthetic 方法没有提供此信息,因此无法使用.并且不存在 Generated 注释.

Surprisingly the isSynthetic method does not give this information so it can't be used. And there is no Generated annotation present.

public class JavaTest {
    public void run() throws Exception {
        out.println(JavaTest.class.getConstructors()[0].isSynthetic()); // Prints false
        out.println(Arrays.asList(JavaTest.class.getConstructors()[0].getAnnotations())); // Prints []
    }
}

这个问题对 C# 提出了同样的问题:在C#中使用反射检测编译器生成的默认构造函数

This question asks the same thing but for C#: Detect compiler generated default constructor using reflection in C#

推荐答案

不,编译器会生成它们:

No, the compiler generates them:

我创建了文件A.java:

public class A{
public String t(){return "";}
}

然后:

javac A.java

并运行javap -c A查看内容:

Compiled from "A.java"
public class A {
  public A();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        

  public java.lang.String t();
    Code:
       0: ldc           #2                  // String 
       2: areturn       
}

如果我添加构造函数:

public A(){}

结果是:

Compiled from "A.java"
public class A {
  public A();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        

  public java.lang.String t();
    Code:
       0: ldc           #2                  // String 
       2: areturn       
}

完全一样.我使用的是带有 64 位 OpenJDK 的 Java 7,但我敢打赌,所有版本都是一样的.

it's identical. I'm using Java 7 with 64 bit OpenJDK, but I'd bet that it's the same with all the versions.

EDIT:实际上,仅使用相同的字节码并不能保证信息不会作为元数据出现.使用十六进制编辑器和 这个程序 可以看到有两个字节不同,并且对应于行号(用于打印堆栈跟踪),因此在这种情况下不存在信息.

EDIT: in fact, the same bytecode alone doesn't guarantee that the information is not present as metadata. Using an hex editor and this program was possible to see that there are two bytes differing, and correspond to the line numbers (used for printing stack traces), so the information is absent in this case.

这篇关于构造函数是否生成默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆