Class/Reflection/getFields()

Dear Friends
Can any one help me to find a solution for the following problem:
I am using a class with inner class and table model. I wanted to get the list of all attributes from both inner and outer classes. All attributes are declared public. I used the Class / Reflection and managed to get the list of attribute in the inner class as shown below. The following code neatly listed all the attributes in the inner class but not the one in outer class.
Class c = classA.innerClassA_.getClass() ;
Try
Field[] fa = c.getFields() ;
For(int i=0; i<fa.length; i++)
Field f = fa;
System.out.println(f) ;
catch(SecurityException se)
Thanks in anticipation,
sunder

You'll need to start with listing all inner classes by using the method:
getDeclaredClasses() in java.lang.Class.
In your case:
classA.class.getDeclaredClasses();Where I presume assume that classA is the class that holds the internal classes.
This will give you an array of all your internal classes.
Given this you can simply find all declared fields in you inner classes.
Hope this was to some help

Similar Messages

  • Inner class reflection

    Hello !
    I have the following class (excerpt):
    public final class Patient
         public Patient()
              //...some code here
         public PatientFilter Filter = new PatientFilter();
         public final class PatientFilter
              public String Pkey = "";
              public String Snm = "";
              public String Fnm1 = "";
              public String Fnm2 = "";
              public void clear()
                   Pkey = "";
                   Snm = "";
                   Fnm1 = "";
                   Fnm2 = "";
    In another .java file I have the following code:
    private void init()
         Patient patient = new Patient();
         ProcessObject(patient);
    private String ProcessObject(Object obj)
         //here I want to call via reflection: patient.Filter.clear();
    So basically I have several "Patient like" classes and I want to call myPatientLikeObject.Filter.clear() from within ProcessObject() function.
    How can I do that?
    Many Thanks,
    Vasile

    OK, these are the java sources :
    Patient.java
    public final class Patient
         public Patient()
              //...some code here
         public PatientFilter Filter = new PatientFilter();
         public final class PatientFilter
              public String Pkey = "";
              public String Snm = "";
              public String Fnm1 = "";
              public String Fnm2 = "";
              public void clear()
                   Pkey = "";
                   Snm = "";
                   Fnm1 = "";
                   Fnm2 = "";
    and Test.java
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    * Created on Jun 30, 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Generation - Code and Comments
    * @author vpurdila
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Generation - Code and Comments
    public class Test
         public Test()
         public static void main(String[] args)
              Test test = new Test();
              test.init();
         private void init()
              Patient patient = new Patient();
              patient.Filter.Snm = "SMITH";
              patient.Filter.Fnm1 = "CAROL";
              ClearObject(patient);
              System.out.println(patient.Filter.Snm);
              System.out.println(patient.Filter.Fnm1);
         public void ClearObject(Object dtoObject)
              //here I want to call via reflection: patient.Filter.clear();
              try
                   Field objFilter = dtoObject.getClass().getDeclaredField("Filter");
                   Method methodClear = objFilter.getType().getDeclaredMethod("clear", new Class[] {});
                   //clear filters
                   methodClear.invoke(objFilter, new Object[] {});
              catch(NoSuchFieldException e)
                   e.printStackTrace();
              catch(InvocationTargetException e)
                   e.printStackTrace();
              catch(IllegalAccessException e)
                   e.printStackTrace();
              catch(NoSuchMethodException e)
                   e.printStackTrace();
              catch(IllegalArgumentException e)
                   e.printStackTrace();
    I'm getting this error when I call "methodClear.invoke(objFilter, new Object[] {});"
    java.lang.IllegalArgumentException: object is not an instance of declaring class
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at Test.ClearObject(Test.java:53)
         at Test.init(Test.java:38)
         at Test.main(Test.java:28)
    Thanks,
    Vasile

  • Problem in generic value copier class / reflection and generic classes

    Hello experts,
    I try to archive the following and am struggling for quite some time now. Can someone please give an assessment if this is possible:
    I am trying to write a generic data copy method. It searches for all (parameterless) getter methods in the source object that have a corresponding setter method (with same name but prefixed by "set" instead of "get" and with exactly one parameter) in the destination object.
    For each pair I found I do the following: If the param of the setter type (T2) is assignable from the return type of the getter (T1), I just assign the value. If the types are not compatible, I want to instantiate a new instance of T2, assign it via the setter, and invoke copyData recursively on the object I get from the getter (as source) and the newly created instance (as destination). The assumption is here, that the occurring source and destination objects are incompatible but have matching getter and setter names and at the leaves of the object tree, the types of the getters and setters are compatible so that the recursion ends.
    The core of the problem I am struggling with is the step where I instantiate the new destination object. If T2 is a non-generic type, this is straightforward. However, imagine T1 and T2 are parametrized collections: T1 is List<T3> and T2 is List<T4>. Then I need special handling of the collection. I can easily iterate over the elements of the source List and get the types of the elements, but I can not instantiate only a generic version of the destinatino List. Further I cannot create elements of T4 and add it to the list of T2 and go into recursion, since the information that the inner type of the destination list is T4 is not available at run-time.
    public class Source {
       T1 getA();
       setA(T1 x);
    public class Dest {
       T2 getA();
       setA(T2 x);
    public class BeanDataCopier {
       public static void copyData(Object source, Object destination) {
          for (Method getterMethod : sourceGetterMethods) {
             ... // find matching getter and setter names
             Class sourceParamT = [class of return value of the getter];
             Class destParamT = [class of single param of the setter];
             // special handling for collections -  I could use some help here
             // if types are not compatible
             Object destParam = destination.getClass().newInstance();
             Object sourceParam = source.[invoke getter method];
             copyData(sourceParam, destParam);
    // usage of the method
    Souce s = new Source(); // this is an example, I do not know the type of s at copying time
    Dest d = new Dest(); // the same is true for d
    // initialize s in a complicated way (actually JAX-B does this)
    // copy values of s to d
    BeanDataCopier.copyData(s, d);
    // now d should have copied values from s Can you provide me with any alternative approaches to implement this "duck typing" behaviour on copying properties?
    Best regards,
    Patrik
    PS: You might have guessed my overall use case: I am sending an object tree over a web service. On the server side, the web service operation has a deeply nested object structure as the return type. On the client side, these resulting object tree has instances not of the original classes, but of client classes generated by axis. The original and generated classes are of different types but have the identically named getter and setter methods (which again have incompatible parameter types that however have consistent names). On the client side, I want to simply create an object of the original class and have the values of the client object (including the whole object tree) copied into it.
    Edited by: Patrik_Spiess on Sep 3, 2008 5:09 AM

    As I understand your use case this is already supported by Axis with beanMapping [http://ws.apache.org/axis/java/user-guide.html#EncodingYourBeansTheBeanSerializer]
    - Roy

  • Class Reflection

    Hi,
    I have a program that scan a folder and load runtime Class descriptor of all java classes inside that folder.
    Then I want to list the classes that are children of a specific interface, specified during runtime.
    Let's say I have read the input and have :
    <code>String myclassname = "Data.class";</code>
    I would need to check using <code>DataClass.isAssignableFrom(<myclasses>)</code>
    The problem is, how do I convert myclassname into Class Data?
    Is there a way to this without using forName method?
    If I had to use forName method, do I need to have the fully qualified name of the class (i.e. package.name.Data) if Data.class is not located in the same package with my program?
    Would it make any difference if I have loaded Data.class during the scanning?
    Thanks

    The problem is, how do I convert myclassname into
    Class Data?You load the class.
    Is there a way to this without using forName method?The class has to be loaded some how. There are variations on the mechanism including class loaders.
    If I had to use forName method, do I need to have the
    fully qualified name of the class (i.e.
    package.name.Data) if Data.class is not located in
    the same package with my program?Classes only and always exist solely with the fully qualified name.

  • Changes made in jsp are not reflected

    webpages are not reflected after modifying jsp pages
    what i need to do??
    thanks in advance

    Hi
    Thanks for your reply,
    I am using CQ 5.5 and was installed service pack 2.
    1. We make package from SVN or through maven build to the CQ dev server.
    2. JSP changes perfect but /var/classes java files contains old code(i.e new JSP file complitation is not happening )
    3. Only when we restart server, /var/classes reflecting with new code other /var/classes have old code only.
    What is best procedure to re-compile JSP with out Restart server.

  • Constructor of package protected class

    Why has class Test no constructor when trying to get the default constructor by reflection.
    class Test {
         public static void main(String[] args){
              try {
                   Class test=Test.class;
                   Constructor[] ctor= test.getConstructors();
                   System.out.println(ctor.length);
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Returns:
    the array of Class objects representing all the
    the declared members of this classWrong citation:
    Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. An array of length 0 is returned if the class has no public constructors, or if the class is an array class, or if the class reflects a primitive type or void.

  • Class.getMethods()

    I have the following code:import java.io.*;
    import java.lang.reflect.*;
    public class Reflection
       public static void main(String[] args)
          Object object = null;
          System.out.print("Enter the name of the class: ");
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          try
             String className = br.readLine();
             object = Class.forName(className).newInstance();
             showMethods(object);
          catch (Exception e) { }
       public static void showMethods(Object passedObject)
          Method[] methods = passedObject.getClass().getMethods();
          for (int x = 0 ; x < methods.length ; x++)
             System.out.println(methods[x]);
          System.out.print("\n" + passedObject.getClass().getName());
          System.out.println(" has access to " + methods.length + " methods.\n");
    }If I enter "java.util.Vector" or "javax.swing.JFrame", I get the correct and expected response.
    If I enter "java.math.BigDecimal" or "java.awt.event.ActionEvent", I get nothing.
    Can anyone explain what I'm missing?
    Thanx to one and all.

    I'm beginning to think that, contrary to what the
    docs say, there is no way to create and use an object
    whose type is not known until runtime:Not entirely true.
    You can find out what the available c'tors are, using reflection. You can pick one, give it some data, and call it. You can use reflection to invoke various methods on that object.
    However, as we've been trying to explain, that's mostly rather pointless.
    Say you set this all up. At runtime you get com class com.acme.RATO. You've never heard of this class before. At compile time, when you're writing the code that will invoke a c'tor and some methods on this class.
    Which c'tor will you invoke? What args will you pass it? Which methods will you invoke? What args? Why?
    Now, I say mostly pointless because you don't have to know at compile time which c'tors, methods, args to use. For something like [url http:/www.beanshell.org]BeanShell, the user provides that stuff at runtime.

  • On reflection

    1.How to design and implement a tree datastructure that can contain arbitrary Objects (what are arbitrary objects?) as data elements in its nodes. The tree should be an n-ary tree (n>2 and varying). The methods in my classes should only use the Java Reflection API to access any class attributes and/or methods it needs. Note: this exercise is a bit artificial and is just there to demonstrate the ability to use the reflection API.
    2. Can the class Class reflect itself?
    Thank you!

    (what are
    arbitrary objects?)I think the assignment just means any arbitrary object -- it's not some special comp sci term. Anything object you can create, you should be able to contain in this data structure you're creating. So this includes Strings, Threads, java.awt.Graphics, Integers, but not primitive types (like an int).
    Otherwise -- do your own homework.

  • Find all symbols that use a class?

    Is there a way to search for symbols by the class they are using? I have a large project, and at times (specifically when refactoring) doing this would be very useful.
    Anyone know?

    Perhaps I should be a little more clear, im talking about from within the CS5 editor, not class reflection.
    Basically in the Symbol list, you can search by symbol name. You can also search by linkage name from the menu. I dont see a way to search by what classes are using what symbols, which is crazy useful when you want to refactor somthing.

  • Reasoning about reflection, your thoughts

    Hello all,
    I would like to have your opinion about the following. To keep things simple, I'll explain my thoughts by referring to the interface java.util.List and the reverse(List) function in java.util.Collections.
    Imagine you have some implementation of List (lets call this class SomeList), which can reverse the elements it holds on a quicker/better/more elegant/etc. way than the algorithm in Collections.reverse(). For example, SomeList can be built as a simply pointer-list, such that reversing the elements is simple a matter of swapping the head and tail-pointer.
    In order to use the power of SomeList when it comes to reversing the elements, whitout having to move the reverse()-function from java.util.Collections to java.util.List (so Somelist can have it's own reverse() function, and ArrayList can use the general algorithm in AbstractList) (*), I thought about implementing java.util.Collections.reverse(List) as following:
    public class Collections
      public static void reverse(List l)
         1) use reflection to check if the inputlist, l, has a function Collections_reverse();
         2)   if l has this function, call l.Collections_reverse()
         3)   if l hasn't this function, run the standard algorithm (the one currently in Collections.reverse()
    }What do you think of this approach? By checking if the given input has a better implementation of the current function, users can override algorithms, even if these algorithms won't be called directly on the class itself. Is this a good use of reflection? Is this all possible? (this might be an odd question, but I don't have much experience with reflection)
    (*) Indeed, I can simple move the reverse(List) function from java.util.Collections to java.util.List, but that doesn't look a good idea to me, since this would also be a reason to move java.util.Collections.sort(List), java.util.Collections.shuffle(List), etc. which will result in an enormous, overloaded, non-simple List-interface at the end.
    thanks a lot for your ideas,
    Peter

    Yeah, marker interfaces are related, however I did intend something different. What I want is to override functions from another class, and to call the overrided function by reflection. I'll give a simple example:
    Assume you have an interface:
    interface CollectionInterface<T>
         public boolean add(T o);
         public boolean remove(T o);
         public Iterator<T> iterator();
    }Also you have a class with static funcions. For example:
    class AlgorithmsOnCollections
         public static <T> int count(CollectionInterface<T> c, int dummy)
    }Countinig the elements in a CollectionInterface is very easy: simply count the elements returned by the iterator:
    class AlgorithmsOnCollections
         public static <T> int count(CollectionInterface<T> c)
              Iterator<T> it = c.iterator();
              int count = 0;
              while (it.hasNext())
                   it.next();
                   ++count;
              return count;
    }However, most collections will have a private member size, which will be incremented/decremented on every add/remove call. AlgorithmsOnCollections has ofcourse no access to it. Therefor I thought about implementing count() as followed:
    class AlgorithmsOnCollections
         public static <T> int count(CollectionInterface<T> c, int dummy)
              Method method = null;
              try
                   method = c.getClass().getMethod("AlgorithmsOnCollections_count", int.class);
                   return (Integer) method.invoke(c, dummy);
              catch (NoSuchMethodException e) // run standard, general-purpose algorithm
                   Iterator<T> it = c.iterator();
                   int count = 0;
                   while (it.hasNext())
                        it.next();
                        ++count;
                   return count;
              catch (IllegalAccessException e)
                   throw new RuntimeException();
              catch (InvocationTargetException e)
                   throw new RuntimeException();
    }Subclasses/implementations of CollectionInterface can decide to 'have' (I'd rather not call it 'implement', since the function isn't in the interface - thats the whole point) the function AlgorithmsOnCollections_count(). If they have it, it will be called by AlgorithmsOnCollections.count(). If they don't have it, the elements will be counted by the iterator.
    What do you think of this? Note that the example is very simple (there is no reason to place simple functions like count() in an external class).
    Here is a fully working example:
    import java.lang.reflect.*;
    import java.util.*;
    interface CollectionInterface<T>
         public boolean add(T o);
         public boolean remove(T o);
         public Iterator<T> iterator();
    class SomeCollection1<T> implements CollectionInterface<T>
         private List<T> elements = new ArrayList<T>();
         public boolean add(T e) { return elements.add(e); }
         public boolean remove(T e) { return elements.remove(e); }
         public Iterator<T> iterator() { return elements.iterator(); }
         public int AlgorithmsOnCollections_count(int dummy) // !! not in CollectionInterface !!
              System.out.println("SomeCollection.count() called!");
              return elements.size();
    class SomeCollection2<T> implements CollectionInterface<T>
         private List<T> elements = new ArrayList<T>();
         public boolean add(T e) { return elements.add(e); }
         public boolean remove(T e) { return elements.remove(e); }
         public Iterator<T> iterator() { return elements.iterator(); }
    class AlgorithmsOnCollections
         public static <T> int count(CollectionInterface<T> c, int dummy)
              Method method = null;
              try
                   method = c.getClass().getMethod("AlgorithmsOnCollections_count", int.class);
                   return (Integer) method.invoke(c, dummy);
              catch (NoSuchMethodException e) // run standard, general-purpose algorithm
                   Iterator<T> it = c.iterator();
                   int count = 0;
                   while (it.hasNext())
                        it.next();
                        ++count;
                   return count;
              catch (IllegalAccessException e)
                   throw new RuntimeException();
              catch (InvocationTargetException e)
                   throw new RuntimeException();
    public class Reflection
         public static void main(String[] args)
              CollectionInterface<Integer> c1 = new SomeCollection1<Integer>();
              CollectionInterface<Integer> c2 = new SomeCollection2<Integer>();
              c1.add(new Integer(10));
              c1.add(new Integer(4320));
              c2.add(new Integer(43));
              c2.add(new Integer(23));
              c2.add(new Integer(169));
              System.out.println(AlgorithmsOnCollections.count(c1, 75));
              System.out.println(AlgorithmsOnCollections.count(c2, 42));
    }The output is:
    SomeCollection.count() called!
    2
    3
    Please let me you know your thoughts! Thanks,
    Peter

  • Access java variable by string name

    Is there a way in java to set a variable by a string name like the $$ option in php?
    What I'm trying to do is set a global String variable from within a loop of key-value pairs. I want to be able to set each variable dynamically without knowing the variable name.
    Instead of doing this:
    this.myVar = newValue;
    I want to do something like:
    this.{"variableName"} = newValue;
    where the string inside the {""} is unknown and comes from data within the loop and one iteration may be "myVar".

    jhowley wrote:
    Well, I kind of thought that wasn't possible and a Map was my backup plan anyway. Thanks for the info.its totally possible with Reflection (but you should use a Map).
    read: [getField(String)|http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getField(java.lang.String)]
    import java.lang.reflect.*;
    public class ReflectionDemo{
    public static void main(String[] args){
         new ReflectionDemo().start();
    public void start(){
         try{
         Class c = this.getClass();
         Field f = c.getDeclaredField("myField");
         int i = f.getInt(this);
         System.out.println(i);
         } catch(Exception e){
         e.printStackTrace();
         int myField = 11;
    }

  • Console on Wblogic 9.2 locking up administration server

    I am upgrading a 7.0 server to 9.2. Its on a real slow and old sun box. Every 3 or 4 things that I do seems to cause the console to stop responding.
    The console worked great in 7.0.
    When I do a prstat on the server I see the process is taking up 47% of the cpu but it never seems to really do anything. The only way I can stop the servers in my WLS instance at this point is to do a kill -9. I have waited up to an hour to see if it ever returns, and it does not.
    Any help would be appreciated.

    Hi,
    The lack of support is always frustrating. If you are getting paid support from BEA, and getting fuzzy answers, you should let them know.
    My experience with BEA, and their support team is the opposite from what you are telling me, they were almost every time very prompt, and knowledgeable. Once every now and then, I do have some issues that they were not able to figure it out, but always very professional.
    The parameter PermSize is a parameter to the JVM, this is independent of WL itself, and this is the minimal size of what is known as permanent generation fold. This is just a chunk of memory reserved to the class loading, class unloading, and class reflection information. Given that a web app server does a lot of class loading/unloading, and given that it looks like WL 9.x is really dependent on the introspection/reflection APIs, this extra memory helps WL performance. If you define the PermSize=128m on your development/testing environment without any issue, this same parameter should work with the production environment (with a production deployment/configuration.) Of course, if you have a server with just the admin console, and a managed server with your app, this should also help the performance (if you can handle the extra memory load.)
    If you are outnumbered on the move to JBoss, you can do nothing, but just remember that JBoss is no heaven either.
    Regards,
    LG

  • What do people think about the different Generic Java approaches?

    I have seen a lot of different approaches for Generic Java, and when people find problems with each approach the normal response has been: the other approach is worse with such and such a problem, do you have a better way?
    The different approaches I have seen are: (in no particular order)
    Please correct me if I am wrong and add other approaches if they are worthy of mention.
    1) PolyJ - by MIT
    This is a completely different approach than the others, that introduces a new where clause for bounding the types, and involves changing java byte codes in order to meet it's goals.
    Main comments were not a java way of doing things and far too greater risk making such big changes.
    2) Pizza - by Odersky & Wadler
    This aims at extending java in more ways than just adding Generics. The generic part of this was replaced by GJ, but with Pizza's ability to use primitives as generic types removed, and much bigger changes allowing GJ to interface with java.
    Main comments were that Pizza doesn't work well with java, and many things in Pizza were done in parallel with java, hence were no longer applicable.
    3) GJ - by Bracha, Odersky, Stoutamire & Wadler
    This creates classes with erased types and bridging methods, and inserts casts when required when going back to normal java code.
    Main comments are that type dependent operations such as new, instanceof, casting etc can't be done with parametric types, also it is not a very intuitive approach and it is difficult to work out what code should do.
    4) Runtime Generic Information - by Natali & Viroli
    Each instance holds information about its Runtime Type.
    Main comments from people were that this consumes way too much memory as each instance holds extra information about its type, and the performance would be bad due to checking Type information at runtime that would have been known at compile.
    5) NextGen - by Cartwright & Steele
    For each parameterized class an abstract base class with types erased is made and then for each new type a lightweight wrapper class and interface are created re-using code from the base class to keep the code small.
    Main comments from people were that this approach isn't as backwards compatible as GJ due to replacing the legacy classes with abstract base classes which can't be instantiated.
    6) .NET common runtime - by Kennedy & Syme
    This was written for adding Generics to C#, however the spec is also targeted at other languages such as VB.
    Main comments from people were that this approach isn't java, hence it is not subject to the restrictions of changing the JVM like java is.
    7) Fully Generated Generic Classes - by Agesen, Freund & Mitchell
    For each new type a new class is generated by a custom class loader, with all the code duplicated for each different type.
    Main comments from people were that the generated code size gets too big, and that it is lacking a base class for integration with legacy code.
    8) JSR-14 - by Sun
    This is meant to come up with a solution Generic Solution to be used in java. Currently it is heavily based on GJ and suffering from all the same problems as GJ, along with the fact that it is constantly undergoing change and so no one knows what to expect.
    See this forum for comments about it.
    As if we didn't have enough approaches already, here is yet another one that hopefully has all of the benefits, and none of the problems of the other approaches. It uses information learnt while experimenting with the other approaches. Now when people ask me if I think I have a better approach, I will have somewhere to point them to.
    (I will be happy to answer questions concerning this approach).
    9) Approach #x - by Phillips
    At compile time 1 type is made per generic type with the same name.
    e.g.class HashSet<TypeA> extends AbstractSet<TypeA> implements Cloneable, Serializable will be translated to a type: class HashSet extends AbstractSet implements Cloneable, SerializableAn instance of the class using Object as TypeA can now be created in 2 different ways.
    e.g.Set a = new HashSet();
    Set<Object> b = new HashSet<Object>();
    //a.getClass().equals(b.getClass()) is trueThis means that legacy class files don't even need to be re-compiled in order to work with the new classes. This approach is completely backwards compatible.
    Inside each type that was created from a generic type there is also some synthetic information.
    Information about each of the bounding types is stored in a synthetic field.
    Note that each bounding type may be bounded by a class and any number of interfaces, hence a ';' is used to separate bounding types. If there is no class Object is implied.
    e.g.class MyClass<TypeA extends Button implements Comparable, Runnable; TypeB> will be translated to a type: class MyClass {
      public static final Class[][] $GENERIC_DESCRIPTOR = {{Button.class, Comparable.class, Runnable.class}, {Object.class}};This information is used by a Custom Class Loader before generating a new class in order to ensure that the generic types are bounded correctly. It also gets used to establish if this class can be returned instead of a generated class (occurs when the generic types are the same as the bounding types, like for new HashSet<Object> above).
    There is another synthetic field of type byte[] that stores bytes in order for the Custom Class Loader to generate the new Type.
    There are also static methods corresponding to each method that contain the implementation for each method. These methods take parameters as required to gain access to fields, contructors, other methods, the calling object, the calling object class etc. Fields are passed to get and set values in the calling object. Constructors are passed to create new instances of the calling object. Other methods are passed when super methods are called from within the class. The calling object is almost always passed for non static methods, in order to do things with it. The class is passed when things like instanceof the generated type need to be done.
    Also in this class are any non private methods that were there before, using the Base Bounded Types, in order that the class can be used exactly as it was before Generics.
    Notes: the time consuming reflection stuff is only done once per class (not per instance) and stored in static fields. The other reflection stuff getting done is very quick in JDK1.4.1 (some earlier JDKs the same can not be said).
    Also these static methods can call each other in many circumstances (for example when the method getting called is private, final or static).
    As well as the ClassLoader and other classes required by it there is a Reflection class. This class is used to do things that are known to be safe (assuming the compiler generated the classes correctly) without throwing any exceptions.
    Here is a cut down version of the Reflection class: public final class Reflection {
      public static final Field getDeclaredField(Class aClass, String aName) {
        try {
          Field field = aClass.getDeclaredField(aName);
          field.setAccessible(true);
          return field;
        catch (Exception ex) {
          throw new Error(ex);
      public static final Object get(Field aField, Object anObject) {
        try {
          return aField.get(anObject);
        catch (Exception ex) {
          throw new Error(ex);
      public static final void set(Field aField, Object anObject, Object aValue) {
        try {
          aField.set(anObject, aValue);
        catch (Exception ex) {
          throw new Error(ex);
      public static final int getInt(Field aField, Object anObject) {
        try {
          return aField.getInt(anObject);
        catch (Exception ex) {
          throw new Error(ex);
      public static final void setInt(Field aField, Object anObject, int aValue) {
        try {
          aField.setInt(anObject, aValue);
        catch (Exception ex) {
          throw new Error(ex);
    }Last but not least, at Runtime one very lightweight wrapper class per type is created as required by the custom class loader. Basically the class loader uses the Generic Bytes as the template replacing the erased types with the new types. This can be even faster than loading a normal class file from disk, and creating it.
    Each of these classes has any non private methods that were there before, making calls to the generating class to perform their work. The reason they don't have any real code themselves is because that would lead to code bloat, however for very small methods they can keep their code inside their wrapper without effecting functionality.
    My final example assumes the following class name mangling convention:
    * A<component type> - Array
    * b - byte
    * c - char
    * C<class name length><class name> - Class
    * d - double
    * f - float
    * i - int
    * l - long
    * z - boolean
    Final Example: (very cut down version of Vector)public class Vector<TypeA> extends AbstractList<TypeA> implements RandomAccess, Cloneable, Serializable {
      protected Object[] elementData;
      protected int elementCount;
      protected int capacityIncrement;
      public Vector<TypeA>(int anInitialCapacity, int aCapacityIncrement) {
        if (anInitialCapacity < 0) {
          throw new IllegalArgumentException("Illegal Capacity: " + anInitialCapacity);
        elementData = new Object[initialCapacity];
        capacityIncrement = capacityIncrement;
      public synchronized void setElementAt(TypeA anObject, int anIndex) {
        if (anIndex >= elementCount) {
          throw new ArrayIndexOutOfBoundsException(anIndex + " >= " + elementCount);
        elementData[anIndex] = anObject;
    }would get translated as:public class Vector extends AbstractList implements RandomAccess, Cloneable, Serializable {
      public static final Class[][] $GENERIC_DESCRIPTOR = {{Object.class}};
      public static final byte[] $GENERIC_BYTES = {/*Generic Bytes Go Here*/};
      protected Object[] elementData;
      protected int elementCount;
      protected int capacityIncrement;
      private static final Field $0 = Reflection.getDeclaredField(Vector.class, "elementData"),
                                 $1 = Reflection.getDeclaredField(Vector.class, "elementCount"),
                                 $2 = Reflection.getDeclaredField(Vector.class, "capacityIncrement");
      static void $3(int _0, Field _1, Object _2, Field _3, int _4) {
        if (_0 < 0) {
          throw new IllegalArgumentException("Illegal Capacity: " + _0);
        Reflection.set(_1, _2, new Object[_0]);
        Reflection.setInt(_3, _2, _4);
      static void $4(int _0, Field _1, Object _2, Field _3, Object _4) {
        if (_0 >= Reflection.getInt(_1, _2)) {
          throw new ArrayIndexOutOfBoundsException(_0 + " >= " + Reflection.getInt(_1, _2));
        ((Object[])Reflection.get(_3, _2))[_0] = _4;
      public Vector(int anInitialCapacity, int aCapacityIncrement) {
        $3(anInitialCapacity, $0, this, $2, aCapacityIncrement);
      public synchronized void setElementAt(Object anObject, int anIndex) {
        $4(anIndex, $1, this, $0, anObject);
    } and new Vector<String> would get generated as:public class Vector$$C16java_lang_String extends AbstractList$$C16java_lang_String implements RandomAccess, Cloneable, Serializable {
      protected Object[] elementData;
      protected int elementCount;
      protected int capacityIncrement;
      private static final Field $0 = Reflection.getDeclaredField(Vector$$C16java_lang_String.class, "elementData"),
                                 $1 = Reflection.getDeclaredField(Vector$$C16java_lang_String.class, "elementCount"),
                                 $2 = Reflection.getDeclaredField(Vector$$C16java_lang_String.class, "capacityIncrement");
      public Vector$$C16java_lang_String(int anInitialCapacity, int aCapacityIncrement) {
        Vector.$3(anInitialCapacity, $0, this, $2, aCapacityIncrement);
      public synchronized void setElementAt(String anObject, int anIndex) {
        Vector.$4(anIndex, $1, this, $0, anObject);
    }Comparisons with other approaches:
    Compared with PolyJ this is a very java way of doing things, and further more it requires no changes to the JVM or the byte codes.
    Compared with Pizza this works very well with java and has been designed using the latest java technologies.
    Compared with GJ all type dependent operations can be done, and it is very intuitive, code does exactly the same thing it would have done if it was written by hand.
    Compared with Runtime Generic Information no extra information is stored in each instance and hence no extra runtime checks need to get done.
    Compared with NextGen this approach is completely backwards compatible. NextGen looks like it was trying to achieve the same goals, but aside from non backwards compatibility also suffered from the fact that Vector<String> didn't extend AbstractList<String> causing other minor problems. Also this approach doesn't create 2 types per new types like NextGen does (although this wasn't a big deal anyway). All that said NextGen was in my opinion a much better approach than GJ and most of the others.
    Compared to .NET common runtime this is java and doesn't require changes to the JVM.
    Compared to Fully Generated Generic Classes the classes generated by this approach are very lightweight wrappers, not full blown classes and also it does have a base class making integration with legacy code simple. It should be noted that the functionality of the Fully Generated Generic Classes is the same as this approach, that can't be said for the other approaches.
    Compared with JSR-14, this approach doesn't suffer from GJ's problems, also it should be clear what to expect from this approach. Hopefully JSR-14 can be changed before it is too late.

    (a) How you intend generic methods to be translated.
    Given that Vector and Vector<Object> are unrelated types,
    what would that type be represented as in the byte code of
    the method? In my approach Vector and Vector<Object> are related types. In fact the byte code signature of the existing method is exactly the same as it was in the legacy code using Vector.
    To re-emphasize what I had said when explaining my approach:
    System.out.println(Vector.class == Vector<Object>.class);  // displays true
    System.out.println(Vector.class == Vector<String>.class);  // displays false
    Vector vector1 = new Vector<Object>(); // legal
    Vector<Object> vector2 = new Vector();  // legal
    // Vector vector3 = new Vector<String>(); // illegal
    // Vector<String> vector4 = new Vector();  // illegal
    Vector<String> vector5 = new Vector<String>();  // legal
    You must also handle the case where the type
    parameter is itself a parameterized type in which the type
    parameter is not statically bound to a ground instantiation.This is also very straightforward: (let me know if I have misunderstood you)
    (translation of Vector given in my initial description)
    public class SampleClass<TypeA> {
      public static void main(String[] args) {
        System.out.println(new Vector<Vector<TypeA>>(10, 10));
    }would get translated as:public class SampleClass {
      public static final Class[][] $GENERIC_DESCRIPTOR = {{Object.class}};
      public static final byte[] $GENERIC_BYTES = {/*Generic Bytes Go Here*/};
      private static final Constructor $0 = Reflection.getDeclaredConstructor(Vector$$C16java_util_Vector.class, new Class[] {int.class, int.class});
      static void $1(Constructor _0, int _1, int _2) {
        try {
          System.out.println(Reflection.newInstance(_0, new Object[] {new Integer(_1), new Integer(_2)}));
        catch (Exception ex) {
          throw (RuntimeException)ex;
      public static void main(String[] args) {
        $1($0, 10, 10);
    }and SampleClass<String> would get generated as:public class SampleClass$$C16java_lang_String {
      private static final Constructor $0 = Reflection.getConstructor(Vector$$C37java_util_Vector$$C16java_lang_String.class, new Class[] {int.class, int.class});
      public static void main(String[] args) {
        SampleClass.$1($0, 10, 10);
    Also describe the implementation strategy for when these
    methods are public or protected (i.e. virtual).As I said in my initial description that for non final, non static, non private method invocations a Method may be passed into the implementing synthetic method as a parameter.
    Note: the following main method will display 'in B'.
    class A {
      public void foo() {
        System.out.println("in A");
    class B extends A {
      public void foo() {
        System.out.println("in B");
    public class QuickTest {
      public static void main(String[] args) {
        try {
          A.class.getMethod("foo", null).invoke(new B(), null);
        catch (Exception ex) {}
    }This is very important as foo() may be overwritten by a subclass as it is here. By passing a Method to the synthetic implementation this guarantees that covariance, invariance and contra variance all work exactly the same way as in java. This is a fundamental problem with many other approaches.
    (b) The runtime overhead associated with your translationAs we don't have a working solution to compare this to, performance comments are hard to state, but I hope this helps anyway.
    The Class Load time is affected in 4 ways. i) All the Generic Bytes exist in the Base Class, hence they don't need to be read from storage. ii) The custom class loader, time to parse the name and failed finds before it finally gets to define the class. iii) The generation of the generic bytes to parametric bytes (basically involves changing bytes from the Constant Pool worked out from a new Parametric type, Utf8, Class and the new Parametric Constant types may all be effected) iv) time to do the static Reflection stuff (this is the main source of the overhead). Basically this 1 time per class overhead is nothing to be concerned with, and Sun could always optimize this part further.
    The normal Runtime overhead (once Classes have been loaded) is affected mainly by reflection: On older JDKs the reflection was a lot slower, and so might have made a noticeable impact. On newer JDKs (since 1.4 I think), the reflection performance has been significantly improved. All the time consuming reflection is done once per class (stored in static fields). The normal reflection is very quick (almost identical to what is getting done without reflection). As the wrappers simply include a single method call to another method, these can be in-lined and hence made irrelevant. Furthermore it is not too difficult to make a parameter that would include small methods in the wrapper classes, as this does not affect functionality in the slightest, however in my testing I have found this to be unnecessary.
    (c) The space overhead (per instantiation)There are very small wrapper classes (one per new Type) that simply contain all non private methods, with single method calls to the implementing synthetic method. They also include any fields that were in the original class along with other synthetic fields used to store reflected information, so that the slow reflection only gets done once per new Type.
    (d) The per-instance space overheadNone.
    (e) Evidence that the proposed translation is sound and well-defined for all relevant cases (see below)Hope this is enough, if not let me know what extra proof you need.
    (f) Evidence for backward compatibility
    (For example, how does an old class file that passes a Vector
    to some method handle the case when the method receives a Vector<T>
    where T is a type parameter? In your translation these types are unrelated.)As explained above, in my approach these are only unrelated for T != Object, in the legacy case T == Object, hence legacy code passing in Vector is exactly the same as passing in Vector<Object>.
    (g) Evidence for forward compatibility
    (How, exactly, do class files that are compiled with a generics compiler run on an old VM)They run exactly the same way, the byte codes from this approach are all legal java, and all legal java is also legal in this approach. In order to take advantage of the Generics the Custom Class Loader would need to be used or else one would get ClassNotFoundExceptons, the same way they would if they tried using Collections on an old VM without the Collections there. The Custom Class Loader even works on older VMs (note it may run somewhat slower on older VMs).
    (h) A viable implementation strategyType specific instantiations are at Class Load time, when the Custom Class Loader gets asked for a new Class, it then generates it.
    The type specific instantiations are never shipped as they never get persisted. If you really wanted to save them all you need to do is save them with the same name (with the $$ and _'s etc), then the class loader would find them instead of generating them. There is little to be gained by doing this and the only reason I can think of for doing such a thing would be if there was some reason why the target VM couldn't use the Custom Class Loader (the Reflection class would still need to be sent as well, but that is nothing special). Basically they are always generated at Runtime unless a Class with the same name already exists in which case it would be used.
    The $GENERIC_DESCRIPTOR and $GENERIC_BYTES from the base class along with the new Type name are all that is required to generate the classes at runtime. However many other approaches can achieve the same thing for the generation, and approaches such as NextGen's template approach may be better. As this generation is only done once per class I didn't put much research into this area. The way it currently works is that the $GENERIC_DESCRIPTOR are basically used to verify that a malicious class files is not trying to create a non Type Safe Type, ie new Sample<Object>() when the class definition said class Sample<TypeA extends Button>. The $GENERIC_BYTES basically correspond to the normal bytes of a wrapper class file, except that in the constant pool it has some constants of a new Parametric Constant type that get replaced at class load time. These parametric constants (along with possibly Utf8 and Class constants) are replaced by the Classes at the end of the new type name, a little more complex than that but you probably get the general idea.
    These fine implementation details don't affect the approach so much anyway, as they basically come down to class load time performance. Much of the information in the $GENERIC_BYTES could have been worked out by reflection on the base type, however at least for now simply storing the bytes is a lot easier.
    Note: I have made a small syntax change to the requested class:
    public T(X datum) --> public T<X>(X datum)
    class T<X> {
      private X datum;
      public T<X>(X datum) {
        this.datum = datum;
      public T<T<X>> box() {
        return new T<T<X>>(this);
      public String toString() {
        return datum.toString();
      public static void main(String[] args) {
        T<String> t = new T<String>("boo!");
        System.out.println(t.box().box());
    }would get translated as:
    class T {
      public static final Class[][] $GENERIC_DESCRIPTOR = {{Object.class}};
      public static final byte[] $GENERIC_BYTES = {/*Generic Bytes Go Here*/};
      private Object datum;
      private static final Field $0 = Reflection.getDeclaredField(T.class, "datum");
      private static final Constructor $1 = Reflection.getDeclaredConstructor(T$$C1T.class, new Class[] {T.class});
      static void $2(Field _0, Object _1, Object _2) {
        Reflection.set(_0, _1, _2);
      static Object $3(Constructor _0, Object _1) {
        try {
          return Reflection.newInstance(_0, new Object[] {_1});
        catch (Exception ex) {
          throw (RuntimeException)ex;
      static String $4(Field _0, Object _1) {
        return Reflection.get(_0, _1).toString();
      static void $5() {
        T$$C16java_lang_String t = new T$$C16java_lang_String("boo!");
        System.out.println(t.box().box());
      public T(Object datum) {
        $2($0, this, datum);
      public T$$C1T box() {
        return (T$$C1T)$3($1, this);
      public String toString() {
        return $4($0, this);
      public static void main(String[] args) {
        $5();
    }as the generic bytes aren't very meaningful and by no means a requirement to this approach (NextGen's template method for generation may work just as well), here are the generated classes with some unused code commented out instead:
    class T$$C28T$$C22T$$C16java_lang_String {
      private T$$C22T$$C16java_lang_String datum;
      private static final Field $0 = Reflection.getDeclaredField(T$$C28T$$C22T$$C16java_lang_String.class, "datum");
    //  private static final Constructor $1 = Reflection.getDeclaredConstructor(T$$C34T$$C28T$$C22T$$C16java_lang_String.class, new Class[] {T$$C28T$$C22T$$C16java_lang_String.class});
      public T$$C28T$$C22T$$C16java_lang_String(T$$C22T$$C16java_lang_String datum) {
        T.$2($0, this, datum);
    //  public T$$C34T$$C28T$$C22T$$C16java_lang_String box() {
    //    return (T$$C34T$$C28T$$C22T$$C16java_lang_String)T.$3($1, this);
      public String toString() {
        return T.$4($0, this);
      public static void main(String[] args) {
        T.$5();
    class T$$C22T$$C16java_lang_String {
      private T$$C16java_lang_String datum;
      private static final Field $0 = Reflection.getDeclaredField(T$$C22T$$C16java_lang_String.class, "datum");
      private static final Constructor $1 = Reflection.getDeclaredConstructor(T$$C28T$$C22T$$C16java_lang_String.class, new Class[] {T$$C22T$$C16java_lang_String.class});
      public T$$C22T$$C16java_lang_String(T$$C16java_lang_String datum) {
        T.$2($0, this, datum);
      public T$$C28T$$C22T$$C16java_lang_String box() {
        return (T$$C28T$$C22T$$C16java_lang_String)T.$3($1, this);
      public String toString() {
        return T.$4($0, this);
      public static void main(String[] args) {
        T.$5();
    class T$$C1T {
      private T datum;
      private static final Field $0 = Reflection.getDeclaredField(T$$C1T.class, "datum");
    //  private static final Constructor $1 = Reflection.getDeclaredConstructor(T$$C6T$$C1T.class, new Class[] {T$$C1T.class});
      public T$$C1T(T datum) {
        T.$2($0, this, datum);
    //  public T$$C6T$$C1T box() {
    //    return (T$$C6T$$C1T)T.$3($1, this);
      public String toString() {
        return T.$4($0, this);
      public static void main(String[] args) {
        T.$5();
    class T$$C16java_lang_String {
      private String datum;
      private static final Field $0 = Reflection.getDeclaredField(T$$C16java_lang_String.class, "datum");
      private static final Constructor $1 = Reflection.getDeclaredConstructor(T$$C22T$$C16java_lang_String.class, new Class[] {T$$C16java_lang_String.class});
      public T$$C16java_lang_String(String datum) {
        T.$2($0, this, datum);
      public T$$C22T$$C16java_lang_String box() {
        return (T$$C22T$$C16java_lang_String)T.$3($1, this);
      public String toString() {
        return T.$4($0, this);
      public static void main(String[] args) {
        T.$5();
    }the methods from the Reflection class used in these answers not given in my initial description are:
      public static final Object newInstance(Constructor aConstructor, Object[] anArgsArray) throws Exception {
        try {
          return aConstructor.newInstance(anArgsArray);
        catch (InvocationTargetException ex) {
          Throwable cause = ex.getCause();
          if (ex instanceof Exception) {
            throw (Exception)ex;
          throw new Error(ex.getCause());
        catch (Exception ex) {
          throw new Error(ex);
      public static final Constructor getDeclaredConstructor(Class aClass, Class[] aParameterTypesArray) {
        try {
          Constructor constructor = aClass.getDeclaredConstructor(aParameterTypesArray);
          constructor.setAccessible(true);
          return constructor;
        catch (Exception ex) {
          throw new Error(ex);
      }

  • Updating a document with category metadata using updateDocument(): error!

    I have studied the sample code and the API docs, and I feel pretty sure I am coding it according to the docs, but I cannot successfully update a document with category metadata. I always get a MetaDataSchemaInvalid exception.
    My process goes like this:
    1. Upload a new file, creating a new document publicobject.
    2. Create a CATEGORY_DEFINITION with all the metadata name/value pairs I wish to write.
    3. Call FileManager.updateDocument() with this CATEGORY_DEFINITION.
    My process differs from the docs in that I am first uploading the document, and then adding the metadata as a second step. I want to get it working this way to make my system more modular. I do not want to make my upload method dependent upon metadata attributes, and vice versa.
    Step 1 is working fine. The document is being uploaded to the right folder. Good to go.
    Step 3 is where I get the error. If the error is my fault, then it must be a result of what I do in step 2. The structure of my CATEGORY_DEFINITION must be messed up.
    Here is my code for creating the CATEGORY_DEFINITION. The Document class is my own entity that encapsulates the binary data for a document, as well as the metadata attributes that are to be assigned to the document once it is uploaded into Content Services. We don't need to worry about where the data comes from. Just assume the raw data is correct.
    public NamedValue[] newCategoryAttributeDefinition(Document document, String categoryDisplayName) throws WebserviceClientException {
    /* Get the category attribute name-value pairs as a 2-D array. */
    Map metadataMap = document.getMetadataParser().getAttributeNameMapping();
    List categoryDefinitionAttributeList = new ArrayList();
    for(Iterator i = metadataMap.entrySet().iterator(); i.hasNext();) {
    Map.Entry entry = (Map.Entry)i.next();
    String name = "CUSTOM_" + (String)entry.getKey();
    Object value = entry.getValue();
    if(value != null) {
    categoryDefinitionAttributeList.add(new Object[] { name, value });
    Object[][] categoryDefinitionAttributeArray = new Object[categoryDefinitionAttributeList.size()][];
    int index = 0;
    for(Iterator i = categoryDefinitionAttributeList.iterator(); i.hasNext();) {
    Object[] value = (Object[])i.next();
    categoryDefinitionAttributeArray[index++] = value;
    /* Create the NamedValue tree that describes this category's attribute values. */
    Long categoryId = new Long(getCategoryClassId(categoryDisplayName));
    NamedValue[] categoryAttributeDefinition = WebserviceUtils.newNamedValueArray(new Object[][] {
    { Options.CATEGORY_ID, categoryId },
    { Options.CATEGORY_DEFINITION_ATTRIBUTES, WebserviceUtils.newNamedValueArray(categoryDefinitionAttributeArray) }
    NamedValue[] categoryDefinition = WebserviceUtils.newNamedValueArray(Options.CATEGORY_DEFINITION, categoryAttributeDefinition);
    return categoryDefinition;
    And below is the resulting CATEGORY_DEFINITION, as seen in a jdb debugger.
    -- The OPT.CATEGORY_ID value is equal to the ID column in ODMV_SCHEMACATEGORY, otherwise known as the category class id.
    -- My OPT.CATEGORY_DEFINITION_ATTRIBUTES tree for this document has the 4 attributes that I want to set. The category has more than these 4 attributes; I am not populating every attribute. None of the attributes are required, and all are editable. I don't need to include every attribute in my CATEGORY_DEFINITION, even if the values are null, do I? Also, all the attribute names start with "CUSTOM_", which I believe is necessary - right?
    -- I am setting only the OPT.CATEGORY_ID and OPT.CATEGORY_DEFINITION_ATTRIBUTES. Am I missing some other required attribute?
    http-8888-Processor5[1] http-8888-Processor5[1] dump categoryDefinition
    categoryDefinition = {
    instance of oracle.ifs.fdk.NamedValue(id=2562)
    http-8888-Processor5[1] dump categoryDefinition[0]
    categoryDefinition[0] = {
    name: "OPT.CATEGORY_DEFINITION"
    value: instance of oracle.ifs.fdk.NamedValue[2] (id=2559)
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    http-8888-Processor5[1] dump categoryDefinition[0].value[0]
    categoryDefinition[0].value[0] = {
    name: "OPT.CATEGORY_ID"
    value: instance of java.lang.Long(id=2558)
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    http-8888-Processor5[1] dump categoryDefinition[0].value[0].value.toString()
    categoryDefinition[0].value[0].value.toString() = "60068"
    http-8888-Processor5[1] dump categoryDefinition[0].value[1]
    categoryDefinition[0].value[1] = {
    name: "OPT.CATEGORY_DEFINITION_ATTRIBUTES"
    value: instance of oracle.ifs.fdk.NamedValue[4] (id=2570)
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    http-8888-Processor5[1] dump categoryDefinition[0].value[1].value[0]
    categoryDefinition[0].value[1].value[0] = {
    name: "CUSTOM_From"
    value: "SA"
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    http-8888-Processor5[1] dump categoryDefinition[0].value[1].value[1]
    categoryDefinition[0].value[1].value[1] = {
    name: "CUSTOM_Footer Number"
    value: "PRM 34-318"
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    http-8888-Processor5[1] dump categoryDefinition[0].value[1].value[2]
    categoryDefinition[0].value[1].value[2] = {
    name: "CUSTOM_To"
    value: "PROJECT TEAM"
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    http-8888-Processor5[1] dump categoryDefinition[0].value[1].value[3]
    categoryDefinition[0].value[1].value[3] = {
    name: "CUSTOM_Subject"
    value: "Riverside Energy Resource Center Meeting Minutes-Internal"
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2564)
    class$oracle$ifs$fdk$NamedValue: instance of java.lang.Class(reflected class=oracle.ifs.fdk.NamedValue, id=1975)
    After building this CATEGORY_DEFINITION, I go on to attempt an update to the document with this information. Here is the method I call. I always fall into the catch(), and the error dump follows the code snippet. Unfortunately, the error doesn't tell me a lot about what's wrong. That's why I am asking for help in spotting any conspicuous errors in my CATEGORY_DEFINITION.
    public Item addCategoryToDocument(Item documentItem,
    NamedValue[] categoryDefinition)
    throws WebserviceClientException {
    FileManager fileManager = getWebserviceClient().getFileManager();
    Item documentItemWithCategory = null;
    try {
    documentItemWithCategory = fileManager.updateDocument(documentItem.getId(), categoryDefinition, null);
    } catch(Exception e) {
    throw new WebserviceClientException("Could not update document with category definition.", e);
    return documentItemWithCategory;
    http-8888-Processor4[1] http-8888-Processor4[1] dump e
    e = {
    detailedErrorCode: "ORACLE.FDK.AggregateError"
    errorCode: "ORACLE.FDK.AggregateError"
    exceptionEntries: instance of oracle.ifs.fdk.FdkExceptionEntry[1] (id=2691)
    info: null
    serverStackTraceId: ""
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2694)
    class$oracle$ifs$fdk$FdkException: instance of java.lang.Class(reflected class=oracle.ifs.fdk.FdkException, id=1972)
    org.apache.axis.AxisFault.log: instance of org.apache.commons.logging.impl.Log4JLogger(id=2695)
    org.apache.axis.AxisFault.faultCode: instance of javax.xml.namespace.QName(id=2696)
    org.apache.axis.AxisFault.faultSubCode: null
    org.apache.axis.AxisFault.faultString: "ORACLE.FDK.AggregateError:ORACLE.FDK.AggregateError"
    org.apache.axis.AxisFault.faultActor: null
    org.apache.axis.AxisFault.faultDetails: instance of java.util.Vector(id=2698)
    org.apache.axis.AxisFault.faultNode: null
    org.apache.axis.AxisFault.faultHeaders: null
    org.apache.axis.AxisFault.class$org$apache$axis$AxisFault: instance of java.lang.Class(reflected class=org.apache.axis.AxisFault, id=1928)
    java.rmi.RemoteException.serialVersionUID: -5148567311918794206
    java.rmi.RemoteException.detail: null
    java.lang.Exception.serialVersionUID: -3387516993124229948
    java.lang.Throwable.serialVersionUID: -3042686055658047285
    java.lang.Throwable.detailMessage: null
    java.lang.Throwable.cause: null
    java.lang.Throwable.stackTrace: instance of java.lang.StackTraceElement[76] (id=2699)
    http-8888-Processor4[1] dump e.exceptionEntries[0]
    e.exceptionEntries[0] = {
    detailedErrorCode: "ORACLE.FDK.MetadataSchemaInvalid"
    errorCode: "ORACLE.FDK.MetaDataError"
    id: 348018
    info: null
    serverStackTraceId: ""
    __equalsCalc: null
    __hashCodeCalc: false
    typeDesc: instance of org.apache.axis.description.TypeDesc(id=2705)
    class$oracle$ifs$fdk$FdkExceptionEntry: instance of java.lang.Class(reflected class=oracle.ifs.fdk.FdkExceptionEntry, id=1973)
    }

    1 – For an existing document, how do I determine what category instances have been applied to it and their attribute values
    FdkSession session = …;
    // Consider we have an existing item myDoc of type document
    Item myDoc = …;
    CommonManager cm = Managers.getCommonManager(session);
    AttributeRequest[] requestedAttributes = new AttributeRequest[]
      // The Categories associated with this Document, if any
    new AttributeRequest(Attributes.CATEGORIES,
      // sub attributerequest
      new AttributeRequest[] {
        // the actual attributes name/values for the category instance – returns a namedvalue array
        new AttributeRequest(Attributes.CUSTOM_ALL,null),
        // the actual category class for the category instance – returns an item
        new AttributeRequest(Attributes.CATEGORY_CLASS_OBJECT,null)
    myDoc = cm.getItem(myDoc.getId(), requestedAttributes);
    log(myDoc); /* output could look like:
    (Item) 14385 DOCUMENT sample3.doc
    requested attributes ...
    CATEGORIES (Item[])=
    (Item) 14387 CATEGORY
    requested attributes ...
    CUSTOM_ALL (NamedValue[])=
    CUSTOM_14352=true (Boolean)
    CUSTOM_14353=Internal Only Pending Review (String)
    CATEGORY_CLASS_OBJECT (Item)=
    (Item) 14354 CATEGORY_CLASS 5044-14351
    This means, that for document sample3.doc, we have 1 instance of a category object applied to it.
    The category object instance has id 14387. The instance is of a category class object type 14354. The instance has two attributes with internal names CUSTOM_14352, and CUSTOM_15353. The values of these attributes are of type Boolean and String respectively.
    2 - How do I update an attribute value of an existing category instance applied to an item
    FdkSession session = …;
    // Consider we have an existing item myDoc of type document
    Item myDoc = …;
    .. perform code along the lines of that shown in step1 above to determine existing category instance info on the document ..
    FileManager fm = Managers.getFileManager(session);
    NamedValue[] categoryInstanceAttributes = new NamedValue[] {
      // use the internal attribute name for all attributes
      new NamedValue("CUSTOM_14352", Boolean.FALSE),
      new NamedValue("CUSTOM_14352", "Company Confidential")
    NamedValue[] categoryDef = new NamedValue[] {
      // the category instance that we are updating
    new NamedValue(Options.UPDATE_CATEGORY_ID,new Long(14387)),
    // the updated values of the category instance
      new NamedValue(Options.CATEGORY_DEFINITION_ATTRIBUTES, categoryInstanceAttributes)
    NamedValue[] documentDef = new NamedValue[] {
    new NamedValue(Options.CATEGORY_DEFINITION, categoryDef)
    requestedAttributes = ...
    myDoc = fm.updateDocument(myDoc.getId(),documentDef,requestedAttributes) ;
    3 – For a document item X, what is the associated category configuration which could include
    a) what are the category objects I can apply on it (either explicitly restricted by way of ALLOWED_CATEGORIES on the folder configuration, or any site/domain category by way of ALLOW_ALL_CATEGORIES)
    b) is there any attribute overrides
    c) is there any enforced categories
    FdkSession session = …;
    // Consider we have an existing item myDoc of type document
    Item myDoc = …;
    CommonManager cm = Managers.getCommonManager(session);
    AttributeRequest[] categoryObjectAttributes = new AttributeRequest[]
    // What is the category object class name
    new AttributeRequest(Attributes.CLASS_NAME,null),
      // What is the category classobject display name
    new AttributeRequest(Attributes.DISPLAY_NAME,null),
    // get attributes inherited and introduced by category object
    new AttributeRequest(Attributes.METADATA_ATTRIBUTES,
      new AttributeRequest[]
        // Attribute internal name
        new AttributeRequest(Attributes.ATTRIBUTE_NAME,null),
        // Attribute display name
        new AttributeRequest(Attributes.DISPLAY_NAME,null),
        new AttributeRequest(Attributes.ATTRIBUTE_TYPE,null),
        new AttributeRequest(Attributes.ATTRIBUTE_DEFAULT,null),
        new AttributeRequest(Attributes.ATTRIBUTE_ENUMERATION,null),
        new AttributeRequest(Attributes.ATTRIBUTE_REQUIRED,null),
        new AttributeRequest(Attributes.ATTRIBUTE_SETTABLE,null),
        new AttributeRequest(Attributes.ATTRIBUTE_UPDATEABLE,null),
        new AttributeRequest(Attributes.ATTRIBUTE_HIDDEN,null),
        new AttributeRequest(Attributes.ATTRIBUTE_PROMPTED,null),
        new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDEABLE,null),
    AttributeRequest[] overrideAttributes = new AttributeRequest[]
    // id of the attribute to be overridden
    new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDE_ATTRIBUTE,null),
    // id of the category class object to which this attribute override applies
    new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDE_CATEGORY_CLASS,null),
    // new default value
    new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDE_DEFAULT,null),
    // should attribute now be prompted
    new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDE_PROMPT,null),
    // is the attribute now required
    new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDE_REQUIRED,null),
    // can instances of this attribute have there value updated
    new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDE_SETTABLE,null),
    AttributeRequest[] requestedAttributes = new AttributeRequest[]
    // what is the category configuration for the item
    new AttributeRequest(Attributes.CATEGORY_CONFIGURATION,
      new AttributeRequest[]
        // Is the category configuration enabled
         new AttributeRequest(Attributes.CONFIGURATION_ENABLED,null),
         // Can the category configuration be overridden or is it final
        new AttributeRequest(Attributes.CONFIGURATION_FINAL,null),
        // What are the required categories for the category configuration and associated attribute information
        new AttributeRequest(Attributes.REQUIRED_CATEGORIES,categoryObjectAttributes),
        // Can any categories in the site be utilized
        new AttributeRequest(Attributes.ALLOW_ALL_CATEGORIES,null),
        // or .. are we restricting the categories to only the following
        new AttributeRequest(Attributes.ALLOWED_CATEGORIES,categoryObjectAttributes),
        // are there any attribute overrides on category object attributes for this category config?
        new AttributeRequest(Attributes.ATTRIBUTE_OVERRIDES,overrideAttributes)
    log(cm.getItem(myDoc.getId(), requestedAttributes); /*
    If ALLOW_ALL_CATEGORIES is set to true, any category in the domain can be utilized that is not abstract. To determine these, the domain item has a property CATEGORY_CLASSES that returns all category objects in the domain. It also has a property ROOT_CATEGORY_CLASSES which returns just the top level categories (those that have no custom category superclass). You would create a sub AttributeRequest[] checking for CLASS_ABSTRACT when requesting the appropriate categories attribute from the domain.
    If ALLOW_ALL_CATEGORIES is set to false, the applicable categories objects that can be utilized on items contained in the folder is determined by the items contained in the ALLOWED_CATEGORIES attribute of the category configuration.
    Finally, the REQUIRED_CATEGORIES attribute list the category items that must be applied to all new items added to the folder.
    4 – How do I manually apply an instance of a category to an existing item
    FdkSession session = …;
    // Consider we have an existing item myDoc of type document
    Item myDoc = …;
    .. use techniques in step3 above to determine what category objects that you planning to apply to the document ..
    .. if the category configuration on the item has ALLOW_ALL_CATEGORIES set to true, you can use any category in the system
    .. otherwise, you must use a category defined in the allowed categories list
    .. the code here is essentially the same as step2 above
    .. you must utilize internal attribute names, and specify the id of the category class object
    FileManager fm = Managers.getFileManager(session);
    NamedValue[] categoryInstanceAttributes = new NamedValue[] {
      // use the internal attribute name for all attributes
      new NamedValue("CUSTOM_14352", Boolean.FALSE),
      new NamedValue("CUSTOM_14352", "Company Confidential")
    NamedValue[] categoryDef = new NamedValue[] {
      // the id of the category object class for which this new category will be an instance of
    new NamedValue(Options.CATEGORY_CLASS_ID,new Long(14354)),
    // the updated values of the category instance
      new NamedValue(Options.CATEGORY_DEFINITION_ATTRIBUTES, categoryInstanceAttributes)
    NamedValue[] documentDef = new NamedValue[] {
    new NamedValue(Options.CATEGORY_DEFINITION, categoryDef)
    requestedAttributes = ...
    myDoc = fm.updateDocument(myDoc.getId(),documentDef,requestedAttributes);
    // Note – it is possible for one to peform creation, updating, and deletion of various category instances for an existing item in the fileManager updateDocument call!
    // you simply supply multiple Options.CATEGORY_DEFINITIONs to the fm.updateDocument call along with any Options.REMOVE_CATEGORY_IDs 5 – How do I specify a category instance when creating a new item
    FdkSession session = …;
    .. use techniques in step3 above to determine what category objects that you planning to apply to the new document ..
    .. you get the category configuration information from the destination folder!!!
    Item destinationFolder = …;
    CommonManager cm = Managers.getCommonManager(session);
    AttributeRequest[] requestedAttributes = new AttributeRequest[]
    // what is the category configuration for the item
    new AttributeRequest(Attributes.CATEGORY_CONFIGURATION,
    destinationFolder = cm.getItem(destinationFolder.getId(),requestedAttributes);.. if the category configuration on the folder item has ALLOW_ALL_CATEGORIES set to true, you can use any category in the system
    .. otherwise, you must use a category defined in the allowed categories list
    .. the code here is essentially the same as step2 above, just we are using createDocument and document definitions now
    .. you must utilize internal attribute names, and specify the id of the category class object
    FileManager fm = Managers.getFileManager(session);
    NamedValue[] categoryInstanceAttributes = new NamedValue[] {
      // use the internal attribute name for all attributes
      new NamedValue("CUSTOM_14352", Boolean.FALSE),
      new NamedValue("CUSTOM_14352", "Company Confidential")
    NamedValue[] categoryDef = new NamedValue[] {
      // the id of the category object class for which this new category will be an instance of
    new NamedValue(Options.CATEGORY_CLASS_ID,new Long(14354)),
    // the attribute values for this new category instance
      new NamedValue(Options.CATEGORY_DEFINITION_ATTRIBUTES, categoryInstanceAttributes)
    String destinationFile = "sample.doc";
    requestedAttributes = new AttributeRequest[]
      new AttributeRequest(Attributes.URL,null)
    Item docDef = fm.createDocumentDefinition(new NamedValue[]
      new NamedValue(Attributes.NAME, destinationFile),
    },requestedAttributes);
    String defURL = ...  // get URL from document definition
    doFileUpload(...)  // upload file using http put to defURL
    NamedValue[] documentDef = new NamedValue[] {
      new NamedValue(Options.USE_SAVED_DEFINITION,new Long(docDef.getId())),
    new NamedValue(Options.DESTFOLDER, new Long(destinationFolder.getId())),
    // specify character set if appropriate
      new NamedValue(Attributes.DOCUMENT_CHARACTER_SET,"ISO-8859-1"),
      // specify language if appropriate
    new NamedValue(Attributes.DOCUMENT_LANGUAGE,"ENGLISH"),
    // apply category instance information
    new NamedValue(Options.CATEGORY_DEFINITION, categoryDef),
    requestedAttributes = ...
    Item doc = fm.createDocument(documentDef,null, requestedAttributes);
    // Note – it is possible for one to peform creation of multiple category instances on a document at the same time
    // you simply supply multiple Options.CATEGORY_DEFINITIONs to the fm.createDocument call
    // Note – that if a folder has a category configuration containing required categories, and you do not specify
    // all applicable category definitions on createDocument, you will receive an FdkException along the lines of
    // missing metadata. You can catch this exception, and retry the createDocument call supplying the valid category definition(s).

  • Oracle optional input parameters

    Hi,
    I have a SP named sp_actualizar_parametr that has 3 input parameters, all of Number type, and one of them is optional.
    How can I do so that my class reflects that situation, how can I passa a null to the optional field?
    now I have:
    public static String setActualizarParametrizacao( int refreshAutoLaG, int refreshAutoNoG, int nUltimasAvariasG){
            CallableStatement pstmt=null;
            try{
                PoolDB poolDB = PoolDB.getPoolDB();
                conn = poolDB.getConnection();
                pstmt = conn.prepareCall("{call pck_w_cfg_templates_parametr.sp_actualizar_parametr(?,?,?,?,?)}");
                pstmt.registerOutParameter(1, OracleTypes.NUMBER);
                pstmt.registerOutParameter(2, OracleTypes.VARCHAR);
                pstmt.setInt(3, refreshAutoLaG);
                pstmt.setInt(4, refreshAutoNoG);
                pstmt.setInt(5, nUltimasAvariasG);
                pstmt.execute();
    ...thanks, V

    Hi,
    I have a SP named sp_actualizar_parametr that has 3 input parameters, all of Number type, and one of them is optional.
    How can I do so that my class reflects that situation, how can I passa a null to the optional field?
    now I have:
    public static String setActualizarParametrizacao( int refreshAutoLaG, int refreshAutoNoG, int nUltimasAvariasG){
            CallableStatement pstmt=null;
            try{
                PoolDB poolDB = PoolDB.getPoolDB();
                conn = poolDB.getConnection();
                pstmt = conn.prepareCall("{call pck_w_cfg_templates_parametr.sp_actualizar_parametr(?,?,?,?,?)}");
                pstmt.registerOutParameter(1, OracleTypes.NUMBER);
                pstmt.registerOutParameter(2, OracleTypes.VARCHAR);
                pstmt.setInt(3, refreshAutoLaG);
                pstmt.setInt(4, refreshAutoNoG);
                pstmt.setInt(5, nUltimasAvariasG);
                pstmt.execute();
    ...thanks, V

Maybe you are looking for