简体   繁体   中英

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. 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?)

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.

class USA extends ffd.tokens.CountryTokens
{

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

} USA country;

Now I have my local variable country of type USA .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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