简体   繁体   English

如何动态创建一个类并在Java中实例化它?

[英]How to dynamically create a class and instantiate it in Java?

I'm fairly new to Java and I am coming to it from a C++ background. 我对Java还是很陌生,我来自C ++。 I am working with a class that has to be extended before it's protected constructor is called. 我正在使用必须在调用受保护的构造函数之前对其进行扩展的类。 I only need the class in one instance. 我只需要一个实例中的类。 Is there a way I can dynamically create the class AND instantiate it at the same time? 有没有一种方法可以动态创建类并同时实例化它?

I found similar posts but not quite hitting the mark. 我发现了类似的帖子,但没有达到目标。 I have the following code as an example but of course it's syntactically incorrect. 我以以下代码为例,但是在语法上当然是错误的。

final ffd.tokens.CountryTokens cToken = new class USA extends ffd.tokens.CountryTokens
{
    USA (String value)
    {
        super(value);
    }
} ("USA");

Something like this? 像这样吗

final ffd.tokens.CountryTokens cToken = new ffd.tokens.CountryTokens("someValue")
{
// override something
};

Corrections: 更正:

Even with protected methods you can create a Builder that will extend ffd.tokens.CountryTokens (pretty crazy huh?) 即使使用受保护的方法,您也可以创建一个扩展ffd.tokens.CountryTokens的Builder(非常疯狂吧?)

public abstract class CountryBuilder extends ffd.tokens.CountryTokens {
   public CountryBuilder () { super("useless-data"); }    
   public abstract ffd.tokens.CountryTokens build (String val); 
}

Using: 使用方法:

CountryBuilder builder = new CountryBuilder (){
   @Override
   public ffd.tokens.CountryTokens build(String val) {
      return new ffd.tokens.CountryTokens(val) {};
   }
};

builder.build("USA");
builder.build("Canada");

I think you get the idea. 我想你应该已经明白了。

I think I got it. 我想我明白了。 I'm always thinking dynamic allocation with Java but if I simply create a local instance I did it this way. 我一直在考虑使用Java动态分配,但是如果我只是创建一个本地实例,我就会这样做。

class USA extends ffd.tokens.CountryTokens
{

    public USA() { super("USA"); }

} USA country;

Now I have my local variable country of type USA . 现在我有了USA类型的本地变量country

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM