🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #15081

Re: Dynamic class selection at run time.

#15081
From: Tom Davies
Date: Fri, 16 Jul 1999 00:00
49 lines
2014 bytes
Barry Kelliher wrote:
> 
> Hi,
> 
>    I would like to know if the following can be done.
> 
>    I have a single class  "class A" which is extended by several classes.
> 
> I originally create a object which is an instance of  class A. |The
> constructor for this class names in it arguments a string which is derived
> from user interaction at run time.  Once a new instance of Class A is
> created  I then want to create an instance of one of the child classes by
> casting. which child class  I chose to  use is determined by one of the
> previously mentioned user input.
> 
> Ok, can I create the instance of the required class with out using a switch
> or if statement? ie can I specify the required class dynamically based on
> the value previously mentioned user input.
> 
> in the statement  ClassName n = new ClassName();   I want to dynamically
> substitute ClassName at run time.

given these classes:

interface Base {
	void foo();
};

/* concrete */ class A implements Base {
	void foo() { System.out.println("I'm an A"); }
};

/* concrete */ class B implements Base {
	void foo() { System.out.println("I'm a B"); }
};

You can say:

String s = ... either "A" or "B"

Base b = (Base)java.lang.Class.forname(s).newInstance();

b.foo();


Does that do what you wanted? Note that there doesn't even have to be a
common base class. Just a common interface.

Tom
Technical Details
Message-ID: <378E7B9A.C3652164@smartchat.net.au>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <7mk8k5$4sg9@forums.borland.com>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,162f723987f8c188
X-Google-Attributes: gidf74b3,public
From: Tom Davies <tom@smartchat.net.au>
Subject: Re: Dynamic class selection at run time.
Date: 1999/07/16
Message-ID: <378E7B9A.C3652164@smartchat.net.au>
X-Deja-AN: 501317923
Content-Transfer-Encoding: 7bit
References: <7mk8k5$4sg9@forums.borland.com>
To: Barry Kelliher <bkelli01@clear.net.nz>
Content-Type: text/plain; charset=us-ascii
Organization: Another Netscape Collabra Server User
Mime-Version: 1.0
Newsgroups: borland.public.jbuilder.java.language