Getting static constants of a class
hi I have this class:
package cl.mejorencasa.pedido.modelos
public class Pedido implements IPedido
public static const ENESPERA:String = "En Espera";
public static const ATENDIENDO:String = "Atendiendo";
public static const ENCOCINA:String = "En Cocina";
public static const FUERADECOCINA:String = "Fuera de Cocina";
public static const ENCAMINO:String = "En Camino";
public static const ENTREGADO:String = "Entregado";
public static const PERDIDOPORREPARTIDOR:String = "Pérdida por Repartidor";
public static const PERDIDOPORCOCINA:String = "Pérdida por Cocina";
public static const CANCELADOPORCLIENTE:String = "Cancelado por Cliente";
public static const CANCELADOPORFALTADEPRODUCTOS:String = "Cancelado Falta Stock";
what I want to do is to create a method that gets all the constants of that class and return them in a ArrayCollection. I must say that I want this method to be dynamic, what I mean is that I want it to go through every constant that are in the class. I don't wan't to add them my self into an ArrayCollection.
The problem is that I don't know how create such a metho, can someone help me?
Thanks a lot.
Sebastián Toro
To see the statics, I think you have to pass the class itself, rather than an instance of the class, to describeType(). So try
describeType(Pedido);
Gordon Smith
Adobe Flex SDK Team
Similar Messages
-
Revision: 10891
Author: [email protected]
Date: 2009-10-06 09:46:47 -0700 (Tue, 06 Oct 2009)
Log Message:
Fix for ASDoc throws error when using getter methods for pseudo-inheritance of static constants
QE notes: None.
Doc notes: None
Bugs: SDK-22676
Tests run: checkintests
Is noteworthy for integration: No
Ticket Links:
http://bugs.adobe.com/jira/browse/SDK-22676
Modified Paths:
flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.javaHave you tried using com.adobe.air.crypto.EncryptionKeyGenerator instead?
-
Use reflection to access static constant
I have a class with a static constant value. Can somebody show me to access the constant value using reflection.
Thanks
Regards,
StephenI have class
public class one{
public static final String TABLE_KEY = "something";
to access the class
one.class.getField(">>what to put here<<") it's static method don't hv any getter method??? -
Right way of defining constants - Interfaces or Classes?
Two widely used ways to define constants in java projects are:
1. Interfaces - Define constants in interfaces, they automatically become static, final and then implement the interface in concrete classes that need those constants.
2. Classes - Use normal classes and define explicitly as static, final. Use CLASS_NAME.CONSTANT_NAME to access the constant in concrete classes.
I have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
"The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from Effective Java, Joshua Bloch
What is your take on this?
RgdsI have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
"The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from Effective Java, Joshua Bloch
I don't like grouping constants into an interface. I prefer keeping them closer to the classes that use them.
% -
How to get the name of a class invoking
Can a method get the name of the class invoking it?
As:
public void myMethod(){
System.out.println("the name of the class invoking this method is: " + XXXXX);
}Edited by: Maria1990 on Aug 17, 2010 8:46 AMMaria1990 wrote:
.getStackTrace() gives me an array with the all details.Or, if you only care about the class, ask a SecurityManager.
public final class ClassUtils {
public static final Class[] getClassContext() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext();
private ClassUtils() {};
public static final Class getCallingClass() { return getClassContext()[2];}
} -
I'm using Oracle 8.1.6 for Linux, and 7.3.4 on HP-UX. Compiler is gcc/g++ 2.95.2
In working with the Oracle precompiler on both HPUX and Linux, I've found a problem with the way that the Linux precompiler generates the sqlctx variable.
On linux, the following is generated when you run the precompiler:
static const unsigned int sqlctx = 1;
However, on HPUX, this is the corresponding code:
static unsigned long sqlctx = 10673468;
When you compile the Linux version with g++/c++ or aCC, you get fatal errors of this nature:
SQLSubsystem.cpp:562: passing `const unsigned int *' as argument 2 of `sqlcxt(void **, unsigned int *, sqlexd *, const sqlcxp *)' discards qualifiers
Is there a way to force the output of proc to leave off the const?
If you view the binary file proc, you can find the static unsigned int string listed. So I think it may be an option. However, I can't seem to turn it on.
Thanks-
Matt WrightAs for sqlctx:
sqlctx is a module identifier variable. i.e. if your project consists of multiple modules, each sqlctx should have different value.
I have seen this error only on Linux Pro*C starting of 8.1.5 version (have not tested 8.0.5 nor 8.1.6).
Anyway, I really can not understand why this error is not patched already.
As for constness:
I can not tell if there is an option which would solve such issue. I can only advise not to use -Werror option of gcc. It generates about 4-5 warnings per module, but it works ;-)) -
Help please: static instance of a class
Hello guys,
I'm quite new to Java (I had abandonned it for years, and now i'm recovering the good habbits) and i am finding trouble with an static instance of a class.
The thing is that I created a JSP page that calls a Java class. My JSP page will be reloaded several times for one same user, therefore, every teme the JSP page is reloaded, a new instance of my Java class is created.
Since I NEEDED to always have the same object of my Java class, I decided to create an static instance of this class. The snippet of my class is:
public class MyClass{
private static MyClass instance = null;
private Vector v=null;
private myClass(){
v = new Vector();
public Vector getItems() {
return this.v;
public static MyClass getInstance() {
if(instance == null) {
instance = new MyClass();
return instance;
For the first time I call getInstance() I get a new instance of MyClass, and if i'm not wrong, the following times I call getInstance(), I should get the same instance, right???
The thing is that I implemented another method that changes the value of Vector v. But when calling this method from the static instance, the change is never reflected on Vector v (every time I try to recover the value of v I get a Null Pointer Exception)
Could anyone tell me what i am doing wrong, please?Is there any other way to do this??
Thanx in advance
Sergiothanks for the answers, but now I have two questions
instead of one:
import java.util.Vector;
public class TestSingleton {
public static void main(String[] args) throws Exception {
MyClass clazz = MyClass.getInstance();
System.out.println("#" +clazz);
clazz.addItem("Test");
clazz.addItem("Hello!");
Vector vec = clazz.getItems();
System.out.println(vec.size());
class MyClass{
private static MyClass instance = null;
private Vector v=null;
private MyClass() {
v = new Vector();
public Vector getItems() {
return this.v;
public void addItem(Object obj) {
this.v.add(obj);
public static synchronized MyClass getInstance() {
if(instance == null) {
instance = new MyClass();
return instance;
}Take a look at this code and see if this answers both your questions.
I love it when the questions multiply! :) -
Require the definition of static members in derived classes
What I would like to do is require the definition of static variable with a particular signature in all implementing/extending classes of T.
I would have thought this could be done in the following way:
public template T
{public static final Object obj;}To me, this says that all classes implementing this interface must define a member with this exact signature. This is not the case.
Basically, I'd like to replicate the behavior I see when I extend a serializable class. I get this warning : "The serializable class X does not declare a static final serialVersionUID field of type long".
Anyone know how to do this? I've googled many search strings, and looks on the forums extensively. I could potentially use code weaving (Aspects), but this adds another level of complexity to my project.
Thanks in advance,
LukeThere is a definite use for it.
I have an ObjectFactory A. Upon initializing a copy of this object, it scans the given package for all classes. Each class is inspected via Reflection. If there is a variable with a particular signature, in my case public static final ObjectFactory.Constructor, we get a copy of the static variable and add it to a TreeMap.
Then, whenever someone calls ObjectFactory.createInstance("class name"), I do a lookup, and invoke a method of the Contructor object to return an instance of that object. Also, the ObjectFactory allows the programmer to list all "extensions" loaded in this manner.
The reason I'm doing this instead of simply putting a static initializer in the "extension" class that would register the extension with the ObjectFactory is:
I want to control when and where extensions are registered.
Does this makes sense?
The only thing I am missing, is how to warn (other than through documentation) the programmer that they need to define this field, exactly in the same manner as classes extended from serialized classes receive a warning that "The serializable class X does not declare a static final serialVersionUID field of type long".
I could do this using Aspect oriented programming, but that adds a layer of complexity that I do not need.
Here is the code:
public class ObjectFactory<T extends Object>
private TreeMap<String,Constructor<T>> cons=new TreeMap<String,Constructor<T>>();
public ObjectFactory(String pkg)
ClassLoader cld=Thread.currentThread().getContextClassLoader();
if(cld==null)
throw new NullPointerException();
String path=pkg.replace(".","/");
URL tmp;
Enumeration<URL> resources;
File dir;
try
resources=cld.getResources(path);
while(resources.hasMoreElements())
try
tmp=resources.nextElement();
dir=new File(URLDecoder.decode(tmp.getPath(), "UTF-8"));
if(dir.exists())
String[] files=dir.list();
for(String file:files)
try
if(file.endsWith(".class"))
Class<?> c=Class.forName(pkg + '.' + file.substring(0, file.length() - 6));
try
Field f=c.getField("constructor");
//TODO add type checking
Constructor<T> con=Constructor.class.cast(f.get(null));
synchronized(cons)
cons.put(con.getName(),con);
System.out.println(con.getName());
catch(IllegalAccessException ignored)
catch(NoSuchFieldException ignored)
catch(ClassNotFoundException e)
catch(UnsupportedEncodingException e)
catch(IOException e)
public interface Constructor<T>
public T createInstance();
public String getName();
public T createInstance(String name) throws FactoryNotFound
Constructor<T> c=cons.get(name);
if(c==null)
throw new FactoryNotFound();
return c.createInstance();
import ObjectFactory.Constructor;
public final class Extension
public static final String desc="";
public static final String name="Test01";
public static final Constructor<Object> constructor=new Constructor<Object>()
public Object createInstance()
return new Fighter();
public String getName()
return name;
} -
Getting Private Constructor of a Class
Hello all,
Is there any way to get the private constructor as we get the public constructors using Class.getConstructors() ?
getConstructors() method is not returning the private constructors, but I need the info about the private constructors also....so if it is possible, please let me know...
Thankstullio0106 wrote:
I know, however it's also impossible to invoke private methods but, using reflection, You can.That's a complete different thing. If the private method is not static, it is invoked on the current instance.
Is it also possible to use private constructors in the same way.
The problem I'm facing is to create a new instance of a class which extends another class and I need to use a private constructor of the superclass (I've no sources of that superclass).First, the Constructor of a class has to invoke a Constructor of a superclass as the first operation (either implicitely invoking an empty constructor or explicitely). There is no way to do any other operation before that. Second, a reflectively fetched Constructor instance always only can create instances of the class it is defined at (using newInstance()). So, yes, you could get access to a private Constructor. With that, you may be able to create a new instance of the class it is defined for. But that's about it. -
Getting static member from Field
Hello,
I have a 'static type safe enum class' and I want to use reflection to implement its toString() method, the String returned should be the name of the field.
(Note that the static instance variables themselves do not have String fields that could be used for the toString() return value.)
I am able to iterate through all fields of the class and print out the names using getName()
But not sure how to compare the types of the fields to a particular type. For example:
for (int i = 0; i < fields.length; i++)
Field field = fields;
// how to compare a field to know if it is a
// particular static instance field
if (field.getType().equals(MyEnum.A_STATIC_INSTANCE))
return field.getName();for (int i = 0; i < fields.length; i++)
Field field = fields;
Object fieldValue = field.get(null);
if (fieldValue == this) return field.getName();
throw new IllegalStateException();Note that [code] tags produce the pretty formatting in this post. -
Using static constants as id in FXML
Is it possible to use a static constant as the id in FXML, and if so how ?
For example if i have a class Person with a static constant defined, such as:
static final String NAMEFIELD = "name";
And then in an FXML file:
<?import Person?>
<TextField id=Person.NAMEFIELD />
The above FXML code generates an error saying that an " is exspected.
I've also tried with "$Person.NAMEFIELD" but that doesn't seem to work either.
Any suggestions ?Is it possible to use a static constant as the id in FXML, and if so how ?Yes, this is supported in JavaFX 2.2:
<TextField>
<id><Person fx:constant="NAMEFIELD"/></id>
</TextField>
The above FXML code generates an error saying that an " is exspected.Quotes are required. FXML must be syntactically valid XML. -
Residence of Constants: Interface vs Class
Hi Gurus
I have a very basic question, while defining constants should we put them
in an interface (say MyConstant) or in a class (say XYZConstant). I am sure, as per java guidelines, they should be in a Constant class and should be used as-
XYZConstant.Constant1because that's for interfaces are not designed.
But...putting them in an interface offers a great ease of use. If any class
wants to use couple of constants just implement that interface and use simply as-
Constant1 and not like XYZConstants.Constant1This saves space, as well as keeps the code readable AND by proper naming
of such interface (say UBSConstant) holding only constants, we can pass the message that this interface is not actually an 'interface' but just a constant holder.
Please comment.
Thanks
Anu... > we can pass the message that this
interface is not actually an 'interface' but
just
a
constant holder.Which is why you shouldn't use an interface forthis
- 'cause that's not what they're for.
http://www.javaworld.com/javaworld/javaqa/2001-06/01-q
a-0608-constants.htmlBelieve me, I have seen constants in interfaces at
numerous places.Believe me, I have seen all manner of things done in numerous places as well, but I don't see that as an argument that such things are correct.
Also even when we know that it's improper to have
interface just for
constants(because the interfaces are not designed for
that), I never
found any disadvantage(If you are talking about the
cohesion, no maintanance
in future would suggest to remove these constants,
moreover I will always
keep my interface in same package and would always
bundle it with any release).
Ok then, with those assumptions I suppose you wouldn't see any disadvantage. I prefer not to assume those things though.
Using Constants in Class, is sometime really
troubling...just imagine long
class name and long constant names (which we would
often have for good
readability..reference Java Naming Standards and put
on top of them that
80 characters / line rule ...again a java coding
standard) turning a line
into two lines...and that code is damn !!!!I tend not to let the amount of typing dictate how I arrange my class hierarchies, but then that might just be me.
setDimensionParameter(
( PropertyControllerConstants.DIMENSION_OF_PROPERTY,
houseSize); This doesn't look bad to me. But again, that might just be me.
>
So is it just! this moral....we should not have
Constants in interface or
should enjoy the freedom of putting qualifier by
implementing constant interface
and using as-
setDimensionParameter( DIMENSION_OF_PROPERTY,
houseSize); Thanks
AnuSo, the maintainer gets to see that all caps unqualified name and check to see if it's a constant in this class, or any super class of this class, or an interface implemented by this class, or an interface implemented by any superclass.
no thanks, I'll just qualify my constants.
But again, that's just me.
Good Luck
Lee -
Static const int attributes and template functions
The following does not link with CC on Solaris9. From what I can glean from the standards committee's notes it looks like it should and it compiles and links fine with g++. If I use a cast in the function call: ("foo((int)B::X)") then it links. If I move the static initialization out of the class definition then it works as well. Should we expect this to work or not?
#include <iostream>
class B
public:
static const int X = 42;
template< typename T > void foo( const T& t ) { std::cout << t << std::endl;}
int main()
foo(B::X);
}The C++ rule (C++ Standard, section 9.4.2 paragraph 4) is that a static const data member of integral type can have an in-class initializer, and the value can be used in integral constant expressions. But if the data member is used, it must be defined outside the class without an initializer. If gcc allows the code, it is by accident. Some other compilers (apart from Sun C++) do not.
Add the line
const int B::X;
somewhere at global scope (or at namespace scope if B is in a namespace) after the declaration of class B. But you can't put this definition in a header file. The entire program must have exactly one definition of the static member. -
Hi,
I want to set the value of a static const to a localised string...
public static const DEFAULT_PROPERTY_NAME:String =
ResourceManager.getInstance().getString(
'strings', 'myVar');
But it is always null...If this compiles, then the problem is that the ResourceManager is loaded with resources AFTER the static initializatino of this class occurs. You'll probalby have the same problem if you make it a static var and initialize it in the declaration of the var. However, you could make it a static var (or maybe even a static const) and initialize in the constructor of the first instance, with code like
public MyClass()
if (DEFAULT_PROPERTY_NAME == null)
DEFAULT_PROPERTY_NAME = ResourceManager.getInstance().getString('strings', 'myVar');
By the time you are constructing instances, the ResourceManager should be loaded with resources.
Gordon Smith, Adobe -
I am trying to install Elements, I get this constant error message. This installation is not supported by this processor type. Contact your product vendor.
I am using Windows 8.Hi,
Which version of Photoshop Elements are you trying to install?
Are you installing from DVD or a download?
If DVD, make sure you are using the Windows one, not the MAC one.
What device are you trying to install on?
Does your system meet the required spec?
Are you on Windows 8 or Windows 8.1?
Brian
Maybe you are looking for
-
Topic titles in Search always showing up in English
We are working with a RoboHelp HTML v8 project with 247 topics. Inside each topic, we are using conditional build tags to mark the content for each language inside each topic. So for each topic file, it has a section of English text, French text, G
-
I get this error when trying to close a title window. TypeError: Error #1009: Cannot access a property or method of a null object reference. at mx.managers::FocusManager/childHideHandler()[E:\dev\4.0.0\frameworks\projects\framework\s rc\mx\mana
-
One of our application users accidently updated approximately 1000 records of one of our Production Database tables .There are 3-5 records usually added /modifiled to this table per day .we also restore a copy of our production database to Test serve
-
MTS variances with moving average price
Hi expert, Is it possible to satisfy this requirement for cost estimate and variances in make to stock scenario ? -Actual cost at Moving average price for all article -Calculate cost estimate for articles and write it on standard price field with str
-
1. Metadata Browser: sort by focal length (using a cushioned range) 2. Ability to filter based on focal length: i.e. with 3 criteria lens, focal length, aperture it would be super simple to paint in presets for removing natural vignetting.