Access dynamically created objects
Hello!
I create some images dynamically by running a for from 1 to a
variable preset. The pictures have the IDs image1, image2 ...
("image"+i). I then add other properties.
Problem is for each I need an onMouseOverHandler thant will
swap the image with another.
I can get the target image with event.currentTarget.id. But I
cannot set it's properties with this["image"+i].source (I need to
change the ones up to that as well) and I cannot access it with
this.getChildByName("image"+i).source either.
What am I doing wrong please?
"M*A*S*H 4077" <[email protected]> wrote in
message
news:go74q6$fbb$[email protected]..
> Hello!
>
> I create some images dynamically by running a for from 1
to a variable
> preset.
> The pictures have the IDs image1, image2 ...
("image"+i). I then add other
> properties.
>
> Problem is for each I need an onMouseOverHandler thant
will swap the image
> with another.
> I can get the target image with event.currentTarget.id.
But I cannot set
> it's
> properties with this["image"+i].source (I need to change
the ones up to
> that as
> well) and I cannot access it with
this.getChildByName("image"+i).source
> either.
>
> What am I doing wrong please?
ID is about as useful as your appendix when you create
objects dynamically.
The event.target property will contain a reference to your
image.
Similar Messages
-
Accessing dynamically created objects
If objects are created dynamically in AS3, using code like
this:
for (var num:Number = 0; num<10; num++){
var txtFld:TextField = new TextField();
txtFld.text = 'This is the original text';
this.addChild(txtFld);
then later, i want to changet the text of one of the
TextFields, how can I do that? The only instance listed in the
variables is a single instance of "txtFld" and it is the last one
that is created. How can I access the others?
ThanksTwo ways pop to my mind.
Give them a name property when you create them and then use
getChildByName().
Push each instance into an array/vector as you create it and
then iterate over the values in the array.
A combination of both? -
Hi
I did not find any way of accessing a dynamically created
object by using notation this[id].
As the code below shows, only hard coded id objects are
recognised by this[id] notation.
Any way to do it ?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.*;
public var l:Label;
public function init():void {
l = new Label();
l.id = 'label1';
l.text = 'firstname';
addChild(l);
public function fred(event:Event):void {
mytextarea1.text+=this['mytextarea1'].name + '\n';
mytextarea1.text+=this['label1'].name + '\n';
]]>
</mx:Script>
<mx:TextArea id="mytextarea1" width="1300"
height="200"/>
<mx:Button click="fred(event)" />
</mx:Application>Thanks guys but I think my example is too simple compared to
my "real world" current problem ...
In my project, I dynamically create containers and children.
I'd like to reach directly a then dynamically created child by its
id, but notation this[id] is not recognised.
A better example : form f1 (id='form1) contains 2 labels (ids
'form1label1' and 'form1label2') ; f1 is included in form f0.
Calling this['form1label1'] crashed even though it is a
declared id control ! The same example using <mx> tags would
not crash...
And I have gone aroud 10000 articles but never found an
answer to this.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.*;
import mx.containers.*;
public function init():void {
var f0:VBox = new VBox();
var f1:VBox = new VBox();
var l:Label;
f0.id = 'form0';
f1.id = 'form1';
l= new Label();
l.id = 'form1label1';
l.text = 'mobile';
f1.addChild(l);
l = new Label();
l.id = 'form1label2';
l.text = 'work';
f1.addChild(l);
f0.addChild(f1);
addChild(f0);
public function fred(event:Event):void {
mytextarea1.text+=Label( this['form1label1'] ).text + '\n';
]]>
</mx:Script>
<mx:TextArea id="mytextarea1" width="1300"
height="200"/>
<mx:Button click="fred(event)" />
</mx:Application> -
Accessing Dynamically created Button
Hi,
Can someone give me an example how to access dynamically created button?
I know how to create a button dynamically but don't know how to access from AS3.
Thanks!Hi,
Please go through following links.
1) http://www.daveoncode.com/2009/05/20/objectcollector-accessing-dynamic-generated-flex-obje cts-by-id/
2) http://stackoverflow.com/questions/6740813/flex-assigning-events-to-dynamically-created-bu ttons
3) http://www.justskins.com/forums/adding-click-event-to-35785.html
Thanks and Regards,
Vibhuti Gosavi | [email protected] | www.infocepts.com -
This[id] doesn't see dynamically created objects????
Hey all!
If i have
<mx:Canvas id="TopCanvas" initialize="Init()">
<mx:Canvas id="VisibleCanvas" >
</mx:Canvas>
</mx:Canvas>
<fx:Script>
function Init(){
var NewO = new Canvas();
NewO.id="InvisibleCanvas";
TopCanvas.addChild(NewO);
if (this["VisibleCanvas"]){
//We can see non-dynamically created canvas
if (this["InvisibleCanvas"]){
//ERROR we cannot see the new one!
Help please! How to access dynamically created Canvases via their id? I know i can save linkage to them in array, but i need to do it through id.
Cheers!If you set the id property on a dynamically created instance, you can check
the id of an instance later if it happens to be a target of an event, for
example. But it will not be assigned to a variable in the document.
By default, MXML generates a non-dynamic class so you can't add properties
to it at runtime. You can set the name property and search the immediate
parent by calling getChildByName, but if the parent is not the document, you
still can't search the document. -
ABAP OBJECTS: Dynamic Create object
Hi folks!
I have a problem... I need to create a dynamic type object with:
<b>DATA: my_instance TYPE REF TO class1.
CREATE OBJECT my_instance TYPE (class2).</b>
<i>* where class1 is a superclass of class2.</i>
When I do:
<b>my_instance ?= m_parent.</b>
<i>* where m_parent is an instance of class1</i>
My problem is when I want to access to an attribute of the class2, the compiler says that it cannot find the attribute <i>(this is OK, because the attribute is only in the class2).</i>
My question:
Is there anyway to access to an atribute of second class when is not in the first class? (i don't want to create the attribute as an attribute of the first class).
Thanx!!!!Hi David,
When you do the debugging, you are dealing with run-time - i.e., the program is now running and you are just interrupting it at each statement to examine the program state. You will reach the point where the object is already created. That is why you can see all those attributes. But when you comiple, the program is not yet <i>running</i>, so the attributes will be unknown because of the dynamic type specification.
I think you will have to redesign the program logic. As i had already said in my earlier post, it is not proper to have the attributes specified statically while the class itself is specified dynamically.
Your situation is somewhat similar to -
DATA ITAB TYPE TABLE OF SPFLI.
PERFORM TEST TABLES ITAB.
FORM TEST TABLES ITAB.
LOOP AT ITAB.
WRITE: / ITAB-CARRID.
ENDLOOP.
ENDFORM.
Hope the point is clear.
Regards,
Anand Mandalika. -
Accessing dynamically created movieclips
I have an application that I am adding movieclips to a
container movieclip through a for loop and repeatedly calling
myClip.addChild(theNewClip). Now I have a dozen clips in my
container and it seems like the only way to access the clip is to
use the getChildByName() method and cast it into a temporary clip
so I can get at the its properties.
Is this the best and/or only way to do this? Does the old AS2
myContainer["theName"].property not work with dynamically created
movieclips? It doesn't seem to work for me anymore.
Anyway I am getting the clips now, but I was hoping someone
could show me a better way to access a dynamically created movie
clip.In AS3, this is probably not much better, but you can
generically loop through all movie clips: -
Access dynamically created JTextField
i need to create an unknown number of JTextField in my GUI, and this number depends on a user-input value.
Subsequently, i will need to read the strings from the JTextField. This is how I dynamically created my JTextField:
while (i < num-1) {
rangePanel.add(new JTextField("0")); // 0 is merely a default value
how can i access the created JTextFields?
thanxIs this the preferred style?
I currently have an array of JTextFields but am having real grief (input on screen not availble fro getText(), etc.), code fragment:
JTextField [] tf = new JTextField[10];
for (i=0, i<10; i++) {
ft[i] = new JTextField(15);
user enters data on screen...
String str = tf[0].getText() returns blank. Also <tab>ing jumps between first position and where ever mouse originally landed in field. -
Accessing Dynamically created Context
Hi,
I want to actually read the context which is dynamically created. I have a basic doubt that, will that context contain all the records or just metadata in context? How to read certain records from the context. I dont want to populate them to view via some textbox etc, actually using that data I want to create some xml. so I need to read all the records which are available in that context.
Please let me know your inputs asap.
Best REgards,
RiteshHi Mehta,
You can create both nodes as well as attributes in context dynamically. If you are creating a context attribute it will have only a single value.If you are creating context nodes it will have multiple values
IWDNode node = wdContext.getChildNode("<node name>",IWDNode.LEAD_SELECTION);
IWDTextview text = (IWDTextview)view,createElement(IWDTextview.class,null)
text.bindText(node.getElementAt(<give index>).getAttribute())
Hope this helps you
Try to create context attributes and nodes statically
Hope this helps you
Regards
Rohit -
HOW TO remove nodes add nodes dynamically create objects branchgroup
After much trial and error, frustration and reading this forum I have come across a good way to dynamically add/remove objects. This is working in my model with 1.3 and jdk 1.4.1_02 Sorry if its sloppy.
Here goes:
Adding objects (cap bits may not be optimised):
(A)
BranchGroup newDynObj = null;
switch (workerType)
case 1: //create a rawEntry BranchGroup
newDynObj = new RawEntry();
break;
case 2: //create a Finshed Node
newDynObj = new FinishedNode();
break;
default:
newDynObj.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
newDynObj.setCapability(BranchGroup.ALLOW_DETACH);
newDynObj.setCapability(Group.ALLOW_CHILDREN_READ);
newDynObj.setCapability(Group.ALLOW_CHILDREN_WRITE);
Transform3D t = new Transform3D();
t.set(scale, new Vector3d(xpos, ypos, zpos));
TransformGroup objTrans2 = new TransformGroup(t);
objTrans2.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objTrans2.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
objTrans2.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
objTrans2.setCapability(TransformGroup.ALLOW_CHILDREN_WRITE);
objTrans2.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
Sphere obj = new Sphere(1.0f, Sphere.GENERATE_NORMALS | Sphere.GENERATE_TEXTURE_COORDS,
5, app);
//add to scene graph
objTrans2.addChild(obj);
newDynObj.addChild(objTrans2);
newDynObj.compile();
return newDynObj;
call this ftn with:
Space3DPanel.objTrans.addChild(createObject(createAppearance(workerType), 0.04, x, y, z, 2)); where objTrans is your tansformGroup
Removing branchgroup:
Its easy to add. But the trick is to delete/remove these !?! Detach doesnt seem to do anything. The method/pattern that works for me is to..
1. make a new class subclassing BranchGroup like this:
public class FinishedEntry extends BranchGroup
{ private String type;
public FinishedEntry(){ }
public FinishedEntry(String type)
{ this.type = type; }
and
public class RawEntry extends BranchGroup
private String type;
public RawEntry(){ }
public RawEntry(String type)
{ this.type = type;}
2. To when adding the BG to the TG of the parent (objTrans)
add a BG of the type you subclassed.
see (A) above.
3. Now scan through the children of the TG that you have been adding these children to. Like this:
static synchronized public void removeNodeFromModel(int workerType)
try {
switch (workerType)
case 1: //raw Entry
for (int i = 0; i < Space3DPanel.objTrans.numChildren(); i++)
if (Space3DPanel.objTrans.getChild(i) instanceof RawEntry)
Space3DPanel.objTrans.removeChild(i);
break;
break;
case 2: //result Entry
for (int i = 0; i < Space3DPanel.objTrans.numChildren(); i++)
if (Space3DPanel.objTrans.getChild(i) instanceof FinishedNode)
Space3DPanel.objTrans.removeChild(i);
break;
} //end for
break;
default:
} catch (Exception e) { e.printStackTrace(); }
The main idea is to use instanceof !! then use removeChild (see above).. Also, you can compile your BGs using this method.
Thanks for the great forum!
Jacob Pyrett
[email protected]First, to add child nodes to a branch group, you must follow two rules:
(1) The child you are adding to the branch group is also a BranchGroup
(2) The BranchGroup.ALLOW_CHILDREN_EXTEND capability is set
From here, you are able to add children on the fly.
To remove a child from the branch group was harder to figure out, but I eventually got it to work. To accomplish this you must do the following:
(1) have the capability BranchGroup.ALLOW_DETACH) set on the child BranchGroup you wish to remove.
(2) call the child's detach() method rather than calling the parent's removeChild()
Hope this helps. -
Dynamically create objects at runtime - Collections?
Dear Experts
During runtime i need to create several objects. Can you help me by pointing out the best practice here? Is it possible to store Man and Dog object in the single collection?
Thank you for the help
The code is as follows
abstract class Mammal {
String name;
Mammal(String n)
name = n;
void sleep()
System.out.println( name + "! is asleep! zzzzzzz!");
abstract void talk();
class Man extends Mammal {
Man(String n)
super(n);
void talk()
System.out.println("H1 My Name is "+name+" How do you do?");
class Dog extends Mammal {
Dog(String n)
super(n);
void talk()
System.out.println("Wrf!Wrf!");
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("Dots");
Man m1 = new Man("Joe");
Dog d2 = new Dog("Dollar");
Man m2 = new Man("Mike");
// ideally i would like to push this into collection of objects
}standman wrote:
thank you
i tried this. If it is wrong please let me know. If all you need is a List, it may work fine. I didn't try it. Some suggestions:
Declare 'al' as a List:
List al = new ArrayList();Then if you decide you need a LinkedList or other List, you only have to change the right side construction.
Try to use generics (as YoungWinston suggested).
Use an Iterator or an "enhanced 'for' loop" for the iteration, instead of constantly checking "size" and using "get(i)". Since you have a short random-access list (ArrayList), your loop may work okay. But, if you had a long non-random-access list (such as LinkedList), an Iterator or "enhanced 'for' loop" (which uses an Iterator behind-the-scenes) would work faster.
If you do need thread-safety, there are other considerations, too. -
Accessing dynamically created fields
Hi,
I have a html that has an input field on it. Say we enter a number( e.g. 5) and submit the html.
The html transfers control to 1. jsp which creates input fields based on the number entered. In the above example 5 input(text) fields are created dynamically.
Once I submit 1.jsp, it transfers control to another 2.jsp.
In 2.jsp, I need to access the values entered in the 5 fields on 1.jsp.
request.getparameter() returns value only from the 1st field (out of the 5 fields). How to access the remaining fields ?
Any help is really appreciated.
Thanks,Thanks a lot. That worked!!!!
Even the ordering seem to be ok.
With your other suggestion, I had tried that before but that did not work.
I created field names as field1,field2..etc on the fly and stored this in a String variable - fileName.
<% fileName = fileName concatinated with number %>
<input type = "text" name=fileName > Note: There are no quotes around fileName. So fileName could be fileName1, fileName2 etc
(I don't think the quotes around name attribute really matters.)
When I say request.getparameter("fileName") it returned only the 1st fileName. Let me know what youythink.
Thanks again. -
Problem with accessing dynamically created movie clips, returns null...
Hopefully this is a stupid question with an easy answer, if my code is straight forward enough.
I am using this snippet of code to create menu items, and then use the jCount variable below to give the clips an index number, like so (which seems to be working just fine):
for(var j:Number=0;j<xmlSubMenuLength;j++){
var mcSubMenuItem:mcSubMenu=new mcSubMenu();
addChild(mcSubMenuItem);
jCount++;
mcSubMenuItem.name = "mcSubMenuItem" + jCount;
//traces out names correctly
trace ("---------------------------------jCount NAME = "+ mcSubMenuItem.name);
mcSubMenuItem.x=mcMenuHolder.x+20;
mcSubMenuItem.y =mcMenuHolder.y;
mcSubMenuItem.y+= nextBtnY;
nextBtnY+=subtopicSpace;
global_subi.text = String(jCount); //i see the proper count of 10 in the text field
However, when I try to access the clips using this snippet:
for(var j:Number=0;j<Number(global_subi.text);j++)//
trace("GLOBAL SUBI = "+ String(global_subi.text)); //traces out 10, which it should
var scSubMenuItem:String = "mcSubMenuItem" + j;
var scSubContent:Object = this.getChildByName(scSubMenuItem);
trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>scSubContent:Object = "+ scSubContent); //returns null!
My last trace statement returns null. Can anyone see my error, or explain why I can't access my clips after they have been created?
Thank you muchly,
~ChiplehHi kglad,
Thanks for the response.
"it's not clear from the shown code that jCount is initialized." - I've posted the relevant code below, which shows that I'm initializing jCount.
"and it's not clear why you don't use j instead of jCount in that for-loop" - j is used as loop for creating the subtopic movie clips within the i for-loop. So, for each topic in i for-loop, create a group of suptopics using the j for-loop. The j for-loop re-initiates j every time the length of the subtopics is reached(if that makes any sense) - i.e. topic1>subtopic 1,2,3,4 : topic2>subtopic>1,2 : topic3>subtopic1,2,3,4
jCount is used to keep a running count of the total number of subtopcs created - i.e. per the example above, jCount will display 10.
var topicSpace:uint=button_mc.height;
var subtopicSpace:uint = button_mc.height;
var nextBtnY:uint = 0;//whatever;
var jCount:Number = 0;
function createXMLMenu(menuLength:Number,itemName:XMLList):void{
var navItemText:XMLList = itemName;
for(var i:Number=0;i<menuLength;i++)
var mcMenuItem:mcMenu=new mcMenu();
addChild(mcMenuItem);
mcMenuItem.btnTxt.htmlText = i+1 +". " +navItemText[i];
mcMenuItem.ivar = i;
mcMenuItem.name = "mcMenuItem" + i;
mcMenuItem.x=mcMenuHolder.x;
mcMenuItem.y =mcMenuHolder.y;
//kglad's addition
mcMenuItem.y+= nextBtnY;
nextBtnY+=topicSpace;
var subVar:Number = i;//mcMenuItem.ivar
//Submenu content
var xmlSubMenuLength:Number = xml.sim.bodyText.page[i].subpage.length()
var menuItemAttachment:MovieClip = MovieClip(mcMenuItem);
for(var j:Number=0;j<xmlSubMenuLength;j++)
var xmlSubPageNumber:XMLList = xml.sim.bodyText.page[subVar].subpage;
var subNavLinkNumber:Number = xmlSubPageNumber[j];
var subTitleText:String = xml.sim.bodyText.page[subVar].subpage.subNavItem[j];
var mcSubMenuItem:mcSubMenu=new mcSubMenu();
trace("mcSubMenuItem.ivar = "+ j+1);
var mc2Attach2:MovieClip = MovieClip(menuItemAttachment);
mcSubMenuItem.btnTxt.htmlText = j+1 +". " +subTitleText;
mcSubMenuItem.ivar = Number(subVar);
mcSubMenuItem.jvar = Number(j);
addChild(mcSubMenuItem);
jCount++;
mcSubMenuItem.name = "mcSubMenuItem" + jCount;
trace ("---------------------------------jCount NAME = "+ mcSubMenuItem.name);
mcSubMenuItem.x=mcMenuHolder.x+20;
mcSubMenuItem.y =mcMenuHolder.y;
//kglad's addition
mcSubMenuItem.y+= nextBtnY;
nextBtnY+=subtopicSpace;
global_subi.text = String(jCount);
mcSubMenuItem.lExtend.visible = false;
global_i.text = String(i);
Then I try to access the clips like so:
-The first for-loop access the topic movie clips, no problem, and traces out scContent correctly.
-The second for-loop traces out null everytime, when I would expect it to be tracing out the names of the subtopic movie clips.
function accessClips(){
//This will access the topic movie clips
for(var i:Number=0;i<Number(global_i.text);i++)
var scMenuItem:String = "mcMenuItem" + i;
var scContent:Object = this.getChildByName(scMenuItem);
trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>scContent:Object = "+ scContent);
//This is supposed to access the subtopic movie clips
for(var j:Number=0;j<Number(global_subi.text);j++)//
var scSubMenuItem:String = "mcSubMenuItem" + j;
var scSubContent:Object = this.getChildByName(scSubMenuItem);
trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>scSubContent:Object = "+ scSubContent);
Hope this makes sense, Chipleh confused. If the code is not clear enough, let me know and I'll try to further clarify.
Thanks again,
~Chipleh -
Reg : Accessing dynamically created attribute
Hi All,
I had created a dynamic node ("demo") and added two attributes ("appid" & "apptext") to it. And also i created three elements for that node and binded the values. Now my dynamic node is having 3 records. I am creating link to action dynamically and binded a action called "onClick". Now in the output i am getting
linktoaction1
linktoaction2
linktoaction3
Now i am stuck with, when i am clicking either of these 3 linktoactions in runtime, i am able to get only the first record. May i know how to traverse through the node. i.e on clicking of linktoaction2 i want to fetch second records of the node and simillarly and linktoaction1 and linktoaction2. I used the following code in "onClick"
IWDNode dynnode = wdContext.currentContextElement().node().getChildNode ("demo",IWDNode.LEAD_SELECTION);
IWDNodeElement ele = dynnode.getCurrentElement();
String text = (String)ele.getAttributeValue("Apptext");
wdComponentAPI.getMessageManager().reportSuccess(text);
Thanks,
Mugundhan.Hi Nikil,
Ya i had assigned only one action for the three linktoactions. I am filling my dynamic node according to the number of records coming from the RFC. How can i pass the index value (i.e) how to identify that which action is being clicked. I am little confused. Thia is what i wrote in my coding,
In Init method,
IWDNodeInfo nodeInfo=wdContext.getNodeInfo().addChild("demo", null,true,true,
true,false,false,true,null,null,null);
nodeInfo.addAttribute("Applid", "com.sap.dictionary.string");
nodeInfo.addAttribute("Apptext", "com.sap.dictionary.string");
IWDNode node = wdContext.wdGetAPI().getRootNode().getChildNode("demo",IWDNode.NO_SELECTION);
for(int i=0; i<wdContext.nodeEt_Mobileportal().size();i++)
IWDNodeElement nodeElem = node.createElement();
nodeElem.setAttributeValue("Applid", wdContext.nodeEt_data().getEt_dataElementAt(i).getApplid());
nodeElem.setAttributeValue("Apptext", wdContext.nodeEt_data().getEt_dataElementAt(i).getApptext());
node.addElement(nodeElem);
In domodify method,
if(firstTime)
IWDTransparentContainer cont= (IWDTransparentContainer)view.getElement("menu");
for( int i=0; i<wdContext.nodeEt_Mobileportal().size(); i++)
IWDLinkToAction link = (IWDLinkToAction)view.createElement(IWDLinkToAction.class,"link"+i);
link.setText(wdContext.nodeEt_Mobileportal().getEt_MobileportalElementAt(i).getApptext());
link.setOnAction(wdThis.wdGetGotoappAction());
cont.addChild(link);
Thanks,
Mugundhan -
Preloading dynamically created objects
Hi,
I have some Object I would like to create on runtime, but it initialization takes some time. So normally I would code something like
Class SimpleFoo
private BigObject bO = new bO("parameters here");
BigObject getBigObject()
return bO;
}but now I have a lot (say around 30 in the total class, which is more complicated) of them, so it would be something like
Class MessyFoo
private BigObject bOprime = new bO("prime parameters here");
private BigObject bOeven = new bO("even parameters here");
BigObject getBigObject(int i)
if (isPrime(i))
return bOprime;
else if (isEven(i))
return bOeven;
}which gets really messy. I'd rather code
Class CleanLookingFoo
BigObject getBigObject(int i)
if (isPrime(i))
return new bO("prime parameters here");
else if (isEven(i))
return new bO("even parameters here");
}but then I miss the caching and initialization advantages. What is the best way to build this? So far my best option is to pre-process the CleanLookingFoo and make a MessyFoo out of it, and then pass it through to the Java compiler, which probably isn't the best solution.The usual pattern is to use a synchronization mechanism and a lazy initialiser. The simplest mechanism is to use a holder class with a static field, since it won't get initialised until it's first used:
public class LazyBigObjects {
static class BigObject {
BigObject (String params) {
System.out.println(params);
static class PrimeBigObjectHolder {
static final BigObject INSTANCE = new BigObject("prime parameters here");
static class EvenBigObjectHolder {
static final BigObject INSTANCE = new BigObject("even parameters here");
public static BigObject getBigObject(int i) {
System.out.println("getBigObject called with " + i);
switch (i) {
case 0: {
return PrimeBigObjectHolder.INSTANCE;
case 1: {
return EvenBigObjectHolder.INSTANCE;
default:
throw new IllegalArgumentException(i + " out of range.");
public static void main (String...args) {
getBigObject(0);
getBigObject(1);
}Output:
getBigObject called with 0
prime parameters here
getBigObject called with 1
even parameters here
The JVM handles synchronisation issues of class initialisation, so you don't need to do anything about that.
Maybe you are looking for
-
ITunes 12.0.1 crashes when restoring iPad 3 iOS 8.1
Hi, I updated our iPad 3 (err the new iPad) to iOS 8.1. In order to do so, I had to do the full restore process. We use W7P64. iTunes now crashes all the time, so we have an iPad with black apps "waiting", and unstable iTunes 12.0.1, it crashes aft
-
Doesn't seem to charge, not being read, and have the sad face
pretty much it. I have the 80G. It was freezing today so i tried restarting it but then it didn't respond to the buttons as if it was on hold but the music was still playing but the screen was frozen. So i hooked it up to a ipod boombox so it would k
-
Start and stop the Communication channel from Java Mapping
How to start and stop the Communication channel from Java Mapping in XI 3.0 Scenario PI - > MQ -> Third Party web application Web application is down and then Communication channels are stop manually . We need to automate this process, MQ Solutio
-
How to view recent logins on apple id?
Hi, I recently got my Iphone 4 stolen and since I got an email saying that the person had reset my Apple ID password. I then reset my password after that and was ust wondering if you could find out recent logins or recent activity in an account? Woul
-
3 keys simultaneously won't work in as3?
I was writing some code for a top-down game in flash CS3 (as3), where a hero would be able to move in 8 directions(using the arrow keys) and shoot (using the spacebar) simultaneously. I ran into a problem with these keys working simultaneously, so I