Class Instance access
Is it possible to make an instance of a class available for
reading / writing to on all documents in an application? If so, how
is it done?
I have an application written that asks a user to login. When
the user enters their information (email / password), information
including their name, email address, date of last login, etc. is
pulled from my database and a class instance is populated on the
current page (lower level page). I would like to reference
different parts of this class instance on multiple documents. For
example, I would like to display a label that has a text property
of "Hello, Jack", where 'Jack' is a variable held in the class
instance on another page at the same level as the current
page.
You need to have a look at the Singleton Pattern. Here is a
link that might help you
http://flexrays.wordpress.com/2007/06/20/singleton-pattern/
Similar Messages
-
Access to Class Instance inside TileList and DataProvider?
I have a TileList that is fed by a DataProvider. The DataProvider places a source Class (and corresponding MovieClip) into the TileList as visual and interactive objects.
dpChords.addItem({ label:tt, source:ChordUnit, data:i, scaleContent:true });
How do I pass unique values to the instances of the "ChordUnit" within the TileList?
public function setChordBin(song:int):void {
var dpChords:DataProvider = new DataProvider();
var i:uint;
// determine chord set
if (song == -1) {
activeChords = allChords;
else {
activeChords = songChordSets[song];
// fill dataProvider
for(i=0; i<activeChords.length; i++) {
var tt = activeChords[i];
dpChords.addItem({ label:tt, source:ChordUnit, data:i, scaleContent:true });
chordBin.dataProvider = dpChords;
// FORMATTING
chordBin.columnWidth = 105;
chordBin.rowHeight = 115;
chordBin.direction = ScrollBarDirection.HORIZONTAL;
chordBin.setStyle("contentPadding", 5);
chordBin.setRendererStyle("imagePadding", 0);
chordBin.scrollPolicy = ScrollPolicy.ON;
// set style for labels
chordBin.setRendererStyle("textFormat", textFormat2);
// set the background skin
chordBin.setStyle("skin", lightBackground);
//set the cell renderer
chordBin.setStyle("cellRenderer", MyTileListRenderer);
// EVENTS
chordBin.addEventListener(ListEvent.ITEM_ROLL_OVER, chordBinItemOVER);
chordBin.addEventListener(ListEvent.ITEM_ROLL_OUT, chordBinItemOUT);
chordBin.addEventListener(ListEvent.ITEM_CLICK, chordBinItemCLICK);Here is the "" Class:
package {
// associates to "ChordUnit" MC graphic in library
import flash.display.*;
import flash.events.*;
import flash.net.URLRequest;
public class ChordUnit extends MovieClip {
public var imagePath:String;
public function ChordUnit():void {
loadDiagramImage(imagePath);
public function loadDiagramImage(imagePath:String) {
trace (imagePath)
var request:URLRequest = new URLRequest(imagePath);
this.diagramView.scaleContent = true;
// this.diagramView.addEventListener(Event.COMPLETE,loadComplete);
// this.diagramView.addEventListener(ProgressEvent.PROGRESS,loadProgress);
this.diagramView.load(request);
Of course, without being able to pass a unique "imagePath" value into the Class instance, the trace is "null". -
Weird classpath issue in EAR.Some classes can access jars that others cant!
Hi,
I'm experiencing a very frustrating problem that's proving to be a bit of a show stopper for me. I would really appreciate some help...
I have an EAR deployed successfully on Sun Appserver 8 which passes the tests from the sun EAR verifier tool. The ear contains a jar file that I built which has a stateless session bean, home, remote interfaces and rmi stubs, deployment descriptors, as well as some utility classes. The EAR also contains some third-party jars such as Hibernate, Log4-j, apache-commons etc etc. The jar I built has in it's manifest file, the classpath information to reference the other jars in the ear.
The problem I am having is that one of the classes in a third-party jar (hibernate3.jar) cannot see a class in another of the third party jars (log4j-1.2.8.jar) and as a result is throwing a NoClassDefFoundError for org/apache/log4j/Layout while trying to initialise - the two jars are at the root of the EAR.
Furthermore, my utility classes can access and use Log4j classes without any problem and logging command from those classes is output successfully to the server console. However, my session bean, which is packaged in the same jar as the utility classes, fails to log anything even though it uses exactly the same logger and log configuration as the utility classses.
I have tried adding classpath information to the manifest of the EAR so that the third-party jars can pick it up but this makes no difference. Also, according to the EAR verifier tool, you are not allowed to put any classpath information in the EAR manifest.
I have also tried deploying this in weblogic but am experiencing the same problem.
If anyone can offer any advice or solutions I would greatly appreciate it.
:)what´s type error have you?
perhaps external libraries (located in classpath) invoke opsCommon.jar and config-3.0.jar classes. then, classnotfound is normal.
and... why separate external libraries (opsCommon.jar and config-3.0.jar inside ear, and other in classpath)? -
How to reference the class-instance, created in parent class.
Hi, I have following scenario. During compilation I am gettting error message -- "cannot resolve symbol - symbol : Variable myZ"
CODE :
under package A.1;
ClassZ
Servlet1
ClassZ myZ = new ClassZ;
under package A.2;
Servlet2 extends Servlet1
myZ.printHi();
How to reference the class-instance created in the parent class?some corrections ...
under package A.1;
ClassZ
Servlet1
init()
ClassZ myZ = new ClassZ;
under package A.2;
Servlet2 extends Servlet1
myZ.printHi(); -
Binding a JavaFX variable to a Java class instance variable
Hi,
I am pretty new to JavaFX but have been developing in Java for many years. I am trying to develop a JavaFX webservice client. What I am doing is creating a basic scene that displays the data values that I am polling with a Java class that extends Thread. The Java class is reading temperature and voltage from a remote server and storing the response in an instance variable. I would like to bind a JavaFx variable to the Java class instance variable so that I can display the values whenever they change.
var conn: WebserviceConnection; // Java class that extends Thread
var response: WebserviceResponse;
try {
conn = new WebserviceConnection("some_url");
conn.start();
Thread.sleep(10000);
} catch (e:Exception) {
e.printStackTrace();
def bindTemp = bind conn.getResponse().getTemperature();
def bindVolt = bind conn.getResponse().getVoltage();
The WebserviceConnection class is opening a socket connection and reading some data in a separate thread. A regular socket connection is used because the server is not using HTTP.
When I run the application, the bindTemp and bindVolt are not updated whenever new data values are received.
Am I missing something with how bind works? Can I do what I want to do with 'bind'. I basically want to run a separate thread to retrieve data and want my UI to be updated when the data changes.
Is there a better way to do this than the way I am trying to do it?
Thanks for any help in advance.
-RichardHi,
If you don't want to constantly poll for value change, you can use the observer design pattern, but you need to modify the classes that serve the values to javafx.
Heres a simple example:
The Thread which updates a value in every second:
// TimeServer.java
public class TimeServer extends Thread {
private boolean interrupted = false;
public ValueObject valueObject = new ValueObject();
@Override
public void run() {
while (!interrupted) {
try {
valueObject.setValue(Long.toString(System.currentTimeMillis()));
sleep(1000);
} catch (InterruptedException ex) {
interrupted = true;
}The ValueObject class which contains the values we want to bind in javafx:
// ValueObject.java
import java.util.Observable;
public class ValueObject extends Observable {
private String value;
public String getValue() {
return this.value;
public void setValue(String value) {
this.value = value;
fireNotify();
private void fireNotify() {
setChanged();
notifyObservers();
}We also need an adapter class in JFX so we can use bind:
// ValueObjectAdapter.fx
import java.util.Observer;
import java.util.Observable;
public class ValueObjectAdapter extends Observer {
public-read var value : String;
public var valueObject : ValueObject
on replace { valueObject.addObserver(this)}
override function update(observable: Observable, arg: Object) {
// We need to run every code in the JFX EDT
// do not change if the update method can be called outside the Event Dispatch Thread!
FX.deferAction(
function(): Void {
value = valueObject.getValue();
}And finally the main JFX code which displays the canging value:
// Main.fx
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import threadbindfx.TimeServer;
var timeServer : TimeServer;
var valueObjectAdapter : ValueObjectAdapter = new ValueObjectAdapter();
timeServer = new TimeServer();
valueObjectAdapter.valueObject = timeServer.valueObject;
timeServer.start();
Stage {
title: "Time Application"
width: 250
height: 80
scene: Scene {
content: Text {
font : Font {
size : 24
x : 10, y : 30
content: bind valueObjectAdapter.value;
}This approach uses less cpu time than constant polling, and changes aren't dependent on the polling interval.
However this cannot be applied to code which you cannot change obviously.
I hope this helps. -
How to get a reference to the owner of a class instance?
Within a method of a class, how can I get a reference to the
object containing the class instance?
To be clear: I have class B that contains a method, say
"myfunc()". Class A (say, the application itself or a custom
component) instantiates a new instance of Class B : myclassB=new
ClassB()
Now, from within myfunc() can I get a reference to Class A?
The simplest way here is to pass a "this" reference when
calling myfunc(), i.e. "myclassB.myfunc(this)" but I would prefer
not to have to remember to always use 'this'.Are these objects within each other. Does classA own classB?
If that is the case, then Greg is correct and it should be
available in parentDocument.
In projects in the past we have created a central
refObjectLocator object that is available to all objects.
Mostly we use events to communicate between objects. Dispatch
an event and let whoever listen for it.
Here is a copy of our reflocator if you are interested.
package com.goconfigure.model {
import mx.collections.ArrayCollection;
import com.adobe.cairngorm.model.ModelLocator;
import com.goconfigure.util.HashMap;
[Bindable]
public class RefObjectLocator implements ModelLocator {
// this instance stores a static reference to itself
private static var refObject : RefObjectLocator;
public var refObjectHM : HashMap = new HashMap();
// singleton: constructor only allows one model locator
public function AppLocator() : void {
if ( RefObjectLocator.refObject != null )
throw new Error( "Only one RefObjectLocator instance should
be instantiated" );
// singleton: always returns the one existing static
instance to itself
public static function getInstance() : RefObjectLocator {
if ( refObject == null )
refObject = new RefObjectLocator();
return refObject;
public function addRefObject( pRefObject : Object, pName :
String ) : void {
refObjectHM.put(pName,pRefObject);
public function getRefObject( pName : String ) : Object {
return refObjectHM.getValue(pName);
public function removeRefObject( pName : String ) : void {
refObjectHM.remove(pName);
public function clearRefObject() : void {
refObjectHM.clear(); -
Getting Class instance of a class
Dear Friends,
I need to get Class instance of a class in my project. Inorder to use the reflection API 's the package name of the class is needed , but it may not be available Only available thing is the name of the class file and the location where that file is existing .
Please suggest some method to get Class instance in this situation.
Shaiju.PYou can create a ClassLoader of your own. There's a simplified example in this thread (reply number 6):
http://forum.java.sun.com/thread.jsp?thread=538836&forum=31 -
11g BPM Global Activity with instance access equivalent ??
Hi,
I want to be able to update an instance variable from a workspace view much as I could with a 10g Global Activity with Instance access.
As always I guess there are a number of solutions (even if they dont match the scenario exactly) but which is the best approach ?
Any help much appreciated.
cheers
TonySame problem ...
I tested with JSP.parameters["arg_myArg"] ... no result -
PAPI WS: Calling a Global Activity with instance Access
Hi,
I have a global activity, which has instance access, and want to call it via PAPI WS. How is this possible? Usually you would use activityExecuteApplication call, but this does not seem to work for activities having instance access.
Regards
MatthiasThe inputs are quite simple, the ProcessID, which is '/SampleProcess' for me and the activity name, which is 'GetData'.
But, of course, this could not work for a Global Activity having instance access. Because in this case an instance id has to be passed in some way, but I don't know, how?
Regards
Matthias -
Converting string into class instance
Hi all,
I want to convert a string which is a class instance in to that class object in the receiving class. I'm sending server's class object as string to another class which is a client.
Please any one suggest to solve this problem.
Thanks& regards,
Sai.do you mean reflection?
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
here is a simple example:
import java.lang.reflect.Field;
public class ThisClass{
public static void main(String[] args) {
try{
System.out.println("Variable Value: " + Variable);
String className = "ThisClass";
String varName = "Variable";
Class c = Class.forName("" + className);
Field f = c.getField("" + varName);
f.setInt(null, 123);
System.out.println("Variable Value: " + Variable);
} catch(Exception e){ System.out.println("Error: " + e); }
public static int Variable = 0;
} -
Get class Instance, and then get hers attributes
Hi Gurus,
i'm new to ABAP Object,
creating an a BSP whit MVC controller i've try to implement the class controller,
but on a method of it i want to get instance of the class parents:
the class that i implement is an extension of CL_BSP_CONTROLLER2.
In this class in the method DO_REQUEST ( for example ) i try to get the instance of the class
parent ( and i got it! ) using this syntax:
data: Parent type ref to IF_BSP_DISPATCHER, " type take from attribute M_PARENT of the class
Parent = ME->M_PARENT.
In debug i see that 'Parent' get rightly the class parent instance but than i want do this:
(i want get the sub controller of the main contoller 'parent', in debug i can see everything fine)
SubController = Parent->GET_ATTRIBUTE(LEFT_CONTROLLER).
But the compiler say that the class instance 'Parent' has no methods and no attribute.
i've try other syntax like:
call METHOD Parent_>GET_ATTRIBUTE
IMPORTING
LEFT_CONTROLLER)
call METHOD ME->M_PARENT->GET_CONTROLLER
EXPORTING
CONTROLLER_ID = 'search'
IMPORTING
CONTROLLER_INSTANCE = Parent2
No one work!
How can i do?
Here screnshot of that i see in debug mode, and that i want get:
http://img190.imageshack.us/i/1debugscreen.jpg/
http://img10.imageshack.us/i/2debugscreen.jpg/
Thanks in advance,
DavideHi Pawan,
classes ref to CL_BSP_CONTROLLER2 like my controller class, have an attribute
M_PARENT type IF_BSP_DISPATCHER.
If the class is a subclass of an main class it has the M_PARENT attribute containing the instance of the parent class,
i can see in debug mode ( here example: http://img40.imageshack.us/img40/1648/3debugscreen.jpg )
i can get this attribute:
data: Parent type ref to IF_BSP_DISPATCHER, " type take from attribute M_PARENT of the class
Parent = ME->M_PARENT.
but the interface IF_BSP_DISPATCHER has no attribute and no method defined, and if i declare 'Parent' as type ref to
CL_BSP_CONTROLLER2 the compiler return error
<=> "The type of "PARENT" cannot be converted to the type of "ME->M_PARENT". "
Davide -
Sending class instance to an external application
Hi,
I was wondering if it is possible to send an instance of a class that has been initialized and instantiated to an external application as a parameter to the application?
Thanks in advance.I dont thin that is posible since the java doc says
Class Class is special cased within the Serialization Stream Protocol. A Class instance is written initially into an ObjectOutputStream in the following format:
TC_CLASS ClassDescriptor
A ClassDescriptor is a special cased serialization of
a java.io.ObjectStreamClass instance.
A new handle is generated for the initial time the class descriptor is written into the stream. Future references to the class descriptor are written as references to the initial class descriptor instance.
So am not sure whether you can create new instances from the deserialized classes. -
Creating custom class instances for XML nodes
Hi guys,
I'm trying to load an external XML document in my application
and create an instance of a custom class for each node in the XML
based on the value of some of their elements. The instances created
will eventually end up in a DataGrid by the way. The problem I'm
having is there seems to be many ways of doing small parts of this
and I have no idea how to make them all gel. Initially I'm using
HTTPService to load the XML file but I've seen people just use an
XML object. Then, after that, I initially set the loaded XML to an
ArrayCollection but others have used XMLList or XMLListCollection.
I've no idea what's the best way to do this.
Eventually, when I've created all of these instances by
looping over the XML and creating them how will I make them
bindable to the data grid? I'm guessing I'll have to group them
somehow...
Any help would be greatly appreciated. ThanksHey Tracy,
That is exactly what I was talking about in a previous post
you replied to
http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?catid=585&threadid=1344350
Anyhow, Below is some code I created to do what your saying
somewhat dynamically. The idea being you can have many different
object types that you may want to populate with data from XML. In
my case I am using e4x as the result type from my web services. At
present I have about 6 different classes that call this function.
I'd love to get some opinions on the function. Good bad or
???? Any improvements etc????
package . . . .
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import mx.utils.ObjectUtil;
* Utility class to convert xml based Objects to class
instances.
* Takes a value object as the destination and an xmlList of
data
* Look through all the items in the value object. Note we
are using classInfo..accessor since
* our objects are bound all variables become getter /
setter's or accessors.
* Also note, we can handle custom objects, arrays and
arrayCollections.
* History
* 03.11.2008 - Steven Rieger : Created class
public final class XMLToInstance
public static function xmlToInstance( destinationObject :
Object, sourceXMLList : XMLList ) : void
// Get the class definition in XML, from the passed in
object ( introspection so to speak )
var classInfo : XML = describeType( destinationObject );
// Loop through each variable defined in the class.
for each ( var aVar : XML in classInfo..accessor )
// If this is String, Number, etc. . . Just copy the data
into the destination object.
if( isSimple( aVar.@type ) )
destinationObject[aVar.@name] = sourceXMLList[aVar.@name];
else
// Dynamically create a class of the appropriate type
var className : String = aVar.@type;
var ObjectClass : Class = getDefinitionByName( className )
as Class;
var newDestObject : Object = Object( new ObjectClass());
// If this is a custom type
if( isCustomType( className ) && ObjectClass != null
// Recursively call itself passing in the custom data type
and the data to store in it.
// I haven't tested nested objects more than one level. I
suppose it should work.
// Note to self. Check.
xmlToInstance( newDestObject, sourceXMLList[aVar.@name] );
else
// Must be some sort of Array, Array Collection . . .
if( ObjectClass != null )
var anXMLList : XMLList = new XMLList(
sourceXMLList[aVar.@name] );
for each( var anItem : XML in anXMLList )
// I'm sure there are more types, just not using any of them
yet.
if( newDestObject is Array )
newDestObject.push( anItem )
else
newDestObject.addItem( anItem );
// Add the data to the destination object. . . .
destinationObject[aVar.@name] = newDestObject;
} // end function objectToInstance
public static function isSimple( dataType : String ) :
Boolean
* This function is pretty self explanatory.
* Check to see if this is a simple data type. Did I miss
any?
* History
* 03.11.2008 - Steven Rieger : Created function
switch( dataType.toLowerCase() )
case "number":
case "string":
case "boolean":
return true;
return false;
} // end isSimple
public static function isCustomType( className : String ) :
Boolean
* This function is pretty self explanatory.
* Check to see if this is a custom data type. Add them here
as you need. . .
* History
* 03.11.2008 - Steven Rieger : Created function
var aClassName : String = className.replace( "::", "."
).toLowerCase();
aClassName = aClassName.substr( aClassName.lastIndexOf( "."
) + 1, aClassName.length - aClassName.lastIndexOf( "." ) );
switch( aClassName )
case "ndatetimevo":
case "expenselineitemvo":
return true;
return false;
} // end isCustomType
} // end class
} // end package -
Passing arguments to a Global Activity with Instance Access
I'm passing arguments to a Global Activity which has Instance access and then I need to assign agrument values to Instance variables. But, somehow arguments not being passed when I enable "Has Instance Access". If I turn instance access off then arguments pass but unfortunately I cannot assign due to instance not being available. Fyi, I'm using WAPI and argument names in HTML form are prefixed with "arg_" as per WAPI documentation.
I would appreciate any help in resolving the issue.
Thanks in advance.
MKSame problem ...
I tested with JSP.parameters["arg_myArg"] ... no result -
Any way to for a class instance to ask what its instance name is?
Hey. I have a class which needs to create a movie clip on the
stage. Since each instance of the class will only ever have 1 movie
clip on the stage at a time, it seems reasonable that I have the
instance create a movie clip with its own name, prefixed with "mc_"
or something of the sort.
Here's where I don't know quite what to do... How do I get at
this information? For instance, when you a dealing with an XMLNode,
you can simply use...
the_answer = xmlNodeInstance.nodeName;
...I know the analogy fails, but hopefully you know what I'm
looking for.
Thanks!hu....
and when you create your movie clip, (assuming you don't just
build it at authoring time) you specify an instance id through the
createEmptyMovieClip function....
taking a cue from this, I'm guessing that my answer is to
change the structure of what I'm doing a little... instantiate my
object with an instance name as a parameter given to the Class
Constructor... that way the class can have it's own name on file.
I guess my only concern there is how do I keep the "name"
variable from being just completely arbitrary...?
I guess I'm getting away from application (becaust I don't
know when I'd do this...) and into theory.... but for instance,
let's say I create my class like this:
var instanceReference:mySuperCoolClass = new
mySuperCoolClass("instanceName");
So. I have my class instance... ideally, the class would
exist on the stage as "instanceName", with "instanceReference"
being another way to reference the instance. That would be ideal...
but how do I make that happen? Because in the scenario of what I've
just done, I see the class instance existing on the stage as
"instanceReference", and I've just passed it a fun, but meaningless
bit of data called "instanceName"...
I suppose I could have the class go back to "_parent" and
create it's own object.... but here again I'm getting into
territory that feels a lot like i have no idea what I'm doing...
haha!
I guess I have enough info to get back to coding for now...
But I'm deffinately open to more tips... I feel like I'm still
missing how a lot of this works.
(I'm at that awkward place where I can easily explain what
OOP is, but I'm far from experienced in how to implement it... I've
only written about half a dozen classes so far... so I still have a
lot to learn. Thanks for your patience, all of you!)
Maybe you are looking for
-
Multiple Apple IDs on iPhone do Find My iPhone?
We need to be able to track my daughter's iPhone. It appears that all devices linked to a Find My iPhone app has to be signed in with the same Apple ID. In that sense, it appears that Find My iPhone is more like Find My Device Running My Apple ID. Is
-
SAP Dialog Instance is not Starting - DISPATCHER EMERGENCY SHUTDOWN
Hi All, We are running on SAP ECC 6.0, Oracle 10, Windows 2003. We have One Central Instance an Two Dialog Instances, we shutdown the SAP system ( Jun 10 15:56:18 2008 ) to do an OFFLINE backup, now one of the Dialog Instances is no starting, we tr
-
G/L account dose not exists in chart of account
Hi every one I have problem in MIRO. My goods receipt is successfully done.But while doing miro system gives error message that " G/L account dose not exists in chart of account ." error is not descriptive .... how would i know which G/L account syst
-
IMac HDMI 'Mirroring' problems with LG 'Full HD' TV
I have my 20" aluminium iMac connected via a mini-DVI/HDMI adapter to my LG 32LF7700 full HD LCD TV. In mirroring mode it's pretty good, but I have two problems. 1. Even when I turn 'Mirroring' off from my Mac's displays 'Menu' options I still have t
-
Change item background color on runtime
Hello i have a List control in my application. What do I have to do to change its items background color on runtime? Thanks