Creating instance of generic type

Hi.
Here is my class
public class ManagerForm<M extends Stuff>{
private Class<M>clazz;
private M manager;
public void setWorker(M manager){
this.manager=manager;
public M getWorker(){
return this.manager;
private final Class<M> getGenericClass() {
Class<M> persistentClass = null;
Type genericType = getClass().getGenericSuperclass();
if (genericType instanceof ParameterizedType) {
ParameterizedType pType = ((ParameterizedType) genericType);
// obtaining first generic type class
persistentClass = (Class<M>) pType.getActualTypeArguments()[0];
return persistentClass;
public ManagerForm(){
this.clazz=getGenericClass();
this.manager=this.clazz.newInstance();
In default constructor I need to inicialize U instance this.user.
I have an nullPointerException in line this.manager=this.clazz.newInstance();
persistantClass is returned nullable because genericType is not instance of ParameterizedType.
Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable.
Thanks in advance.

YoungWinston wrote:
877715 wrote:
Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable. I think you need to back up and explain exactly what you're trying to do here.
It would appear that you're attempting to divine the actual type of a specific ManagerForm, but I'm not absolutely certain. Also, since you already specify the type as a field, why can't you just usemanager.getClass()? I suspect that all you'll get from getClass().getGenericSuperclass() is 'Stuff', but I have to admit I'm no expert on this.
Far better to describe what you want than an implementation that plainly doesn't work.
WinstonWell. I have class ManagerForm<M extends Stuff>. there is private field manager that have generic type M. And I need to instantinate manager in default constructor.
I cant write
public ManagerForm(){
this.manager=new M();//will be compiler error
Thats why exists a mechanism to get current generic type in runtyme through ParameterType.
I have method getGenericClass that gets current class in runtime and then I create an instance of this class through <class>.newInstance(); And this is the standard way to instantinate generic type.
I hoped line Type genericType = getClass().getGenericSuperclass(); of method returned ParameterizedType. But variable genericType cannot be casted to ParameterizedType. I don't know why. So I cannot get current generic param M and instantiate its.

Similar Messages

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Trouble creating instance of generic container

    Hi,
    I'm new to generics and having problem with a member initialization. The member in question is a Map where the key is a String and the values are Lists of String. Here's my most recent attempt:
    private Map<String,List<String>> m_dimProps = new HashMap<String,new ArrayList<String>( )>( );
    If I comment out the initialization and replace it with null the compiler doesn't complain so I know that the left hand side is right. Help!
    -ts1971

    ts1971 wrote:
    private Map<String,List<String>> m_dimProps = new HashMap<String,new ArrayList<String>( )>( );Parameterizations do not take objects but type names as parameters:
    private Map<String,List<String>> m_dimProps = new HashMap<String,List<String>>( );

  • Instantiation of generic type

    Hi.
    I have an issue with instantiating of generic type. My issue is similar to this Re: creating instance of generic type post.
    So I have the following class
    public class VehicleForm<V extends Vehicle>{
    private V vehicle;
    private Double price;
    private Class<V>vItemClass;
    public V getVehicle(){
    return this.vehicle;
    public void setVehicle(V vehicle){
    this.vehicle=vehicle;
    public Double getPrice(){
    return this.price;
    public void setPrice(Double price){
    this.price=price;
    private final Class<V> getGenericClassInstance() {
    Class<V> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<V>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public VehicleForm(){
    this.vItemClass=getGenericClassInstance();//vItemClass is null
    this.vehicle=this.vItemClass.newInstance();//null poiner exception
    I cannot write in default constructor
    public VehicleForm(){
    this.vehicle=new V();//runtime error will occure
    because of generic type
    For obtaining generics we can use java reflection functionality. Generic type list in runtime is obtaining through ParameterizedType. The code in getGenericClassInstance is standard to instantiate generic type var.
    But unfortunately in my case it doesn't work. getGenericClassInstance returns null. Line Type genericType = getClass().getGenericSuperclass(); doesnt get generic type which is instance of ParameterizedType, so the condition if (genericType instanceof ParameterizedType) is false. My genericType is Object instance, but not ParameterizedType. So I cannot create Class<V> instance from null.
    Can anybody help me? Thanks in advance.
    Edited by: 877736 on 06.08.2011 12:50
    Edited by: 877736 on 06.08.2011 12:51

    877736 wrote:
    My issue is similar to this Re: creating instance of generic type post...Did you look at the answers given there? Pretty much the same as ttjacobs is telling you here: This is NOT what generics was created for.
    Even if you can do it, the code is likely to be messy, complex and brittle.
    Also: this thread is in the wrong category, as the other poster (you?) was already told. There is a "Generics" section under Java APIs.
    My suggestion: rethink your solution.
    Winston

  • New instance of a generic type?

    Hello!
    I'm quite new to writing generics and I have this (possibly lame) question: how can I create a new instance of a generic type?
    Let's say that inside a class MyClass<T> I have a method with following interface, whose only purpose would be to return new instance of the generic type T: public T getInstance(); Inside this method, I tried the obvious way of getting that instance, that is return new T(); and I also understood why that cannot be done.
    However, Googling didn't really reveal any other ways of doing this, so I'm a little stuck. Could anybody please show me the light here?

    triceo wrote:
    However, Googling didn't really reveal any other ways of doing this.Because there aren't any.
    triceo wrote:
    Could anybody please show me the light here?Search this forum. I doubt you'd have to go back more than a few hours to find the last time this question was asked.

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • BAPI_PO_CRETE1:No instance of object type PurchaseOrder has been created

    Hi All,
    It's very urgent,can u plz guide me how to use <b>BAPI_PO_CRETE1</b>
    I am getting the folowing errorrs while creating,<b>esp the error 1</b>
    can u plz guide me what are all the parameters to to pass to suppress this error
    <b>1. No instance of object type PurchaseOrder has been created. External reference:</b>
    2. Purchase order still contains faulty items
    3. Please only use sites with local currency EUR
    4. Net price for item 00010 taken from conditions
    Thanks in advance.
    Best Regards,
    Vishnuvardhan reddy.

    there are mandotary fields in ur bapi that have to b filled in, and u have to check the item elemant of how many characters it requires if the data elemant if 5 charaters u have to fill in the precceding with a number of zero here is a sample code of creating a Po with a single line item
    REPORT zak_testing .
    CONSTANTS : c_x VALUE 'X'.
    ***Structures to hold PO schedule data
    **DATA : itemschedule LIKE bapimeposchedule OCCURS 0 WITH HEADER *LINE ,
    **itemschedulex LIKE bapimeposchedulx OCCURS 0 WITH HEADER LINE .
    *Structures to hold PO header data
    DATA : header LIKE bapimepoheader ,
    headerx LIKE bapimepoheaderx .
    *Structures to hold PO account data
    DATA : account LIKE bapimepoaccount OCCURS 0 WITH HEADER LINE ,
    accountx LIKE bapimepoaccountx OCCURS 0 WITH HEADER LINE .
    *Internal Tables to hold PO ITEM DATA
    DATA : item LIKE bapimepoitem OCCURS 0 WITH HEADER LINE,
    itemx LIKE bapimepoitemx OCCURS 0 WITH HEADER LINE,
    *Internal table to hold messages from BAPI call
    return LIKE bapiret2 OCCURS 0 WITH HEADER LINE,
    *Internal table to hold messages from BAPI call
    pocontractlimits LIKE bapiesucc OCCURS 0 WITH HEADER LINE.
    DATA : w_header(40) VALUE 'PO Header',
    purchaseorder LIKE bapimepoheader-po_number,
    delivery_date LIKE bapimeposchedule-delivery_date.
    DATA : ws_langu LIKE sy-langu.
    header-comp_code = '01'.
    header-doc_type = 'NB'.
    header-vendor = '0000101111'.
    header-creat_date = sy-datum.
    header-purch_org = '0001'.
    header-pur_group = '502'.
    header-doc_date = sy-datum.
    *header-quot_date = sy-datum.
    *append header.
    *POPULATE HEADER FLAG.
    headerx-comp_code = c_x.
    headerx-doc_type = c_x.
    headerx-vendor = c_x.
    headerx-creat_date = c_x.
    headerx-purch_org = c_x.
    headerx-pur_group = c_x.
    headerx-doc_date = c_x.
    *populate ur item table
    item-po_item = '00010'. " note item in Quotes
    item-acctasscat = 'K'.
    item-short_text =  'workforce labour'.
    item-matl_group = '904045'.
    item-plant = '0002'. " depending if 0002 plant exist in ur database
    item-quantity = '1'.
    item-po_unit = 'EA'.
    item-net_price = '1000000'.
    item-price_unit = '1'.
    APPEND item.
    CLEAR item.
    *POPULATE ITEM FLAG TABLE
    itemx-po_item = '00010'. "notice that item has to b passes in every instance
    itemx-po_itemx = c_x.
    itemx-acctasscat = c_x.
    itemx-short_text = c_x.
    itemx-matl_group = c_x.
    itemx-plant = c_x.
    itemx-quantity = c_x.
    itemx-po_unit = c_x.
    itemx-net_price = c_x .
    itemx-price_unit = c_x.
    APPEND itemx.
    CLEAR itemx..
    itemx-material = c_x.itemx-net_price = c_x
    *POPULATE ACCOUNT DATA.
    account-po_item = '00010'.
    account-creat_date = sy-datum .
    account-gr_rcpt = 'MTCD FS'.
    account-unload_pt = 'Woodstock'.
    account-costcenter = '0000120010'.
    account-gl_account = '0000455655'.
    *account-CO_AREA    = 'MTCD FS'.
    account-serial_no = serial .
    APPEND account.
    CLEAR account.
    *POPULATE ACCOUNT FLAG TABLE.
    accountx-po_item = '00010'.
    accountx-po_itemx = c_x.
    accountx-creat_date = c_x .
    accountx-gr_rcpt = c_x.
    account-unload_pt = c_x.
    accountx-costcenter = c_x.
    accountx-gl_account = c_x .
    APPEND accountx.
    CLEAR accountx.
    APPEND itemx. CLEAR itemx.
    **POPULATE ITEM SCHEDULE DATA.
    **POPULATE ITEM FLAG FOR SCHEDULE TABLE.
    *BAPI CALL
    CALL FUNCTION 'DIALOG_SET_NO_DIALOG'.
    CALL FUNCTION 'BAPI_PO_CREATE1'
         EXPORTING
              poheader         = header
              poheaderx        = headerx
         IMPORTING
              exppurchaseorder = purchaseorder
         TABLES
              return           = return
              poitem           = item
              poitemx          = itemx
              poaccount        = account
              poaccountx       = accountx.
    *Confirm the document creation by calling database COMMIT
    CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'
         EXPORTING
              wait = 'X'.
    IF NOT header IS INITIAL.
      CALL FUNCTION 'DEQUEUE_ALL'.
    ELSE.
      CALL FUNCTION 'DEQUEUE_ALL'.
    **message i036.
    ENDIF.
    try this n substitute the code where relavent

  • No instance of object type PurchaseRequisition has been created.External re

    Dear experts,
           I used the bapi:BAPI_PR_CREATE to create PR, occurs below error.
    No instance of object type PurchaseRequisition has been created. External reference: A0460-0013
    Can you tell me how to resolve ?
    CALL FUNCTION 'BAPI_PR_CREATE'
          EXPORTING
           PRHEADER                    = PRHEADER
           PRHEADERX                   = PRHEADERX
             TESTRUN                     = 'X'
           IMPORTING
            NUMBER                      =  PR_NO
            PRHEADEREXP                 =
            TABLES
             RETURN                      = PR_RETURN
              PRITEM                      = PRITEM
              PRITEMX                     = PRITEMX
              PRITEMEXP                   =  PRITEMEXP
            PRITEMSOURCE                =
             PRACCOUNT                   = PRACCOUNT
            PRACCOUNTPROITSEGMENT       =
            PRACCOUNTX                  = PRACCOUNTX
            PRADDRDELIVERY              = PRACCOUNTX
            PRITEMTEXT                  =
            PRHEADERTEXT                =
            EXTENSIONIN                 =
            EXTENSIONOUT                =
            PRVERSION                   =
            PRVERSIONX                  =
            ALLVERSIONS                 =

    Hi Merry,
    I think you are missing some of the mandatory fields for this BAPI, thats why you are getting this error.
    Check all the fields filled and also PRHEADERX, that have you filled X for all the fields filled in PRHEADER.
    Regards,
    Nitin.

  • No instance of object type PurchaseOrder has been created. External referen

    Hi Friends,
    We are on SRM 5.0 SP11, R/3 4.7 backend.
    When we try to create a PO manually in SRM PO doesnot get created, but we get this error message in application monitors of RZ20  - "No instance of object type PurchaseOrder has been created. External reference: "
    I have looked at the note 973952 but this is not applicable for our system.
    any help on this ???
    Regards,
    Kumar
    Edited by: Kumar on Apr 23, 2008 1:35 PM

    Hi all,
    @Dinesh: I have checked all the settings mentioned by you and they are in place.
    @David: the other errors following this issue are
    PurchOrder 0800000024: PO header data still faulty
    PO 0800000024: Document type ECPO not allowed with doc. category F (Please check input)
    PurchOrder 0800000024: Item category not allowed with document type ECPO.
    As suggested by Hitender, I tired to push the PO manually throgh the function module and now in RZ20 i get the error as PO 0800000024: Document number 800000024 not within defined inter val
    But I checked the number ranges in both the systems and they looks fine...
    This is ECS scenario:
    In SRM System I have maintained the number ranges for local PO as 08     0800000001     0899999999     800000030     
    and in R/3 08     0800000001     0899999999     800000030     X(ext flag selected).
    Please advice whether this is correct.. I have also checked the Document types item categories.....
    Regards,
    Kumar

  • BAPI 001 No instance of object type purchaseorder has been created

    Hello All,
    I get teh following error message in SC monitor (backend application error) as well as in RZ20. I tried to push into backend but no luck.Scenario Classic.SRM 5.0
    Shopping cart XXXXX(PO XXXXX) BAPI 001 No instance of object type purchaseorder has been created.
    The latest log in BBP_PD
    0000000001 I1111          Item in Transfer Process       X
    0000000001 I1112          Error in transmission
    Any clue is appreciated.
    Muthu
    Edited by: Muthuraman Govindasamy on Oct 7, 2008 2:59 PM

    Hi Andrea
    We can create a PO vis sourcing cockpit in classic mode.
    SC: Error in transmission BAPI 001
    Note :- 973952 and follow the Peter instructions. This error  message misleads
    regards
    Muthu

  • Error: No instance of object type PurchaseOrder has been created.

    Hi:
    I am using BAPI_PO_CREATE1 to create PO's using webdynpro. I get the following error message when I attempt to create a PO.
    No instance of object type PurchaseOrder has been created. External reference:
    Please help.
    Thanks
    Sriram

    Ramki:
    Yes, I did. The initialization code is as follows
    Bapi_Po_Create1_Input input = new Bapi_Po_Create1_Input();
    input.setPoheader(new Bapimepoheader());
    input.setPoheaderx(new Bapimepoheaderx());
    input.addPoitem(new Bapimepoitem());
    input.addPoitemx(new Bapimepoitemx());
    input.addPoaccount(new Bapimepoaccount());
    input.addPoaccountx(new Bapimepoaccountx());
    input.addPoschedule(new Bapimeposchedule());
    input.addPoschedulex(new Bapimeposchedulx());
    input.addPotextheader(new Bapimepotextheader());
    Thanks
    Sriram

  • BAPI 001 No instance of object type PurchaseOrder has been created. Externa

    HI,
    we have the below mentioned issue when we are creating SC through describe requirement.
    BAPI 001 No instance of object type PurchaseOrder has been created. External reference:  (Document Number XXXXXXXXXXX
    06 213 Error in net price calculation, item 000010 (Please correct)  (Document Number XXXXXXXXXXX)
    we are trying to assign the inforrecord when we are creating the SC through describe requirement.
    Could any one suggest what is going wrong
    regards
    subbu

    this error is misleading error message from SRM SIDE . click follow on document icon via monitor sc. you will get real error message in application monitor or rz20.
    check the real error message in rz20.
    update here what is ther error message...
    muthu

  • Generics' types at runtime (JVM)

    Hi everybody
    This is gonna be a tricky question I guess.
    I'm using generics for an application of mine and I need to know the actual types of a class at runtime.
    For example, let's say I have: "Hashtable<String, Integer> ht;"
    Using Reflection I can easily find out that 'ht' is an 'Hashtable' as well as I can create an instance of Hashtable.
    But if I use 'ht.getTypeParameters()' to find out the type of the generics, I get '<K,V>' instead of
    '<String,Integer>', this because 'ht.getTypeParameters()' returns the formal types and not the actual types.
    In the same way, "Class.forName("java.util.Hashtable");" works, while
    "Class.forName("java.util.Hashtable<String,Integer>");" throws an exception because it can't find the class,
    Does anybody of you know if and how it is possible to access actual generics types at runtime?
    Thanks in advance
    michele

    Not possible. That's why we call it erasure ;-)
    There is an RFE to reify generic type arguments at runtime:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5098163

  • New Effective CAL essay: How do I create an abstract data type in CAL?

      <p><strong>How do I create an abstract data type in CAL?</strong></p>  <p> </p>  <p>An <em>abstract data type</em> is one whose internal representation can be changed without needing to modify the source code of client modules that make use of that type. For software maintainability, it is a good idea to make a type that is subject to change or enhancement into an abstract data type. Another reason to create an abstract data type is to enforce invariants for values of the type that can only be ensured by using <em>constructor functions</em> (i.e. functions that return values of that type).</p>  <p> </p>  <p>In principle it is simple to create an abstract data type in CAL. For an algebraic data type, make the type constructor public and all data constructors private. For a foreign data type, make the type constructor public and the implementation scope private. If a scope qualifier is omitted, the scope is taken to be private.</p>  <p> </p>  <p>For example, the Map algebraic data type has the public type constructor Map and the data constructors Tip and Bin are each private, so it is an abstract data type.</p>  <p> </p>  <p>/** A map from keys (of type {@code k@}) to values</p>  <p>   (of type {@code a@}). */</p>  <p><strong>data</strong> <strong>public</strong> Map k a <strong>=</strong></p>  <p>    <strong>private</strong> Tip <strong>|</strong></p>  <p>    <strong>private</strong> Bin</p>  <p>        size      <strong>::</strong> <strong>!</strong>Int</p>  <p>        key       <strong>::</strong> <strong>!</strong>k</p>  <p>        value     <strong>::</strong> a</p>  <p>        leftMap   <strong>::</strong> <strong>!(</strong>Map k a<strong>)</strong></p>  <p>        rightMap  <strong>::</strong> <strong>!(</strong>Map k a<strong>);</strong></p>  <p><strong> </strong></p>  <p><strong> </strong></p>  <p>There are a number of invariants of this type: the size field represents the number of elements in the map represented by its Bin value. The keys in leftMap are all less than key, which in turn is less than all the keys in rightMap.  In particular, non-empty Map values can only be created if the key parameter type is a member of the Ord type class.</p>  <p> </p>  <p>Values of the Map type can be created outside the Cal.Collections.Map module only by using constructor functions such as insert:</p>  <p> </p>  <p>insert <strong>::</strong> Ord k <strong>=></strong> k <strong>-></strong> a <strong>-></strong> Map k a <strong>-></strong> Map k a<strong>;</strong></p>  <p><strong>public</strong> insert <strong>!</strong>key value <strong>!</strong>map <strong>= ...</strong></p>  <p> </p>  <p>The owner of the Cal.Collections.Map module must ensure that all invariants of the Map type are satisfied, but if this is done, then it will automatically hold for clients using this function.</p>  <p> </p>  <p>Some examples of foreign abstract data types are Color, StringNoCase  and RelativeDate:</p>  <p> </p>  <p><strong>data</strong> <strong>foreign</strong> <strong>unsafe</strong> <strong>import</strong> <strong>jvm</strong> <strong>private</strong> "java.awt.Color"</p>  <p>    <strong>public</strong> Color<strong>;</strong></p>  <p><strong> </strong></p>  <p><strong>data</strong> <strong>foreign</strong> <strong>unsafe</strong> <strong>import</strong> <strong>jvm</strong> <strong>private</strong> "java.lang.String"</p>  <p>    <strong>public</strong> StringNoCase<strong>;</strong></p>  <p><strong> </strong></p>  <p><strong>data</strong> <strong>foreign</strong> <strong>unsafe</strong> <strong>import</strong> <strong>jvm</strong> <strong>private</strong> "int"</p>  <p>    <strong>public</strong> RelativeDate<strong>;</strong></p>  <p> </p>  <p>The private implementation scope for Color means that a foreign function whose type involves Color can only be declared in the Cal.Graphics.Color module where the Color type is defined. A foreign function declaration involving the Color type relies on the compiler knowing that the Color type corresponds to java.awt.Color to resolve the corresponding Java entity i.e. it must know about the implementation of the Color type. Having a private implementation scope means that the Color type can be changed to correspond to a different Java class, or indeed to be an algebraic type, without the risk of breaking client code.</p>  <p> </p>  <p>In all these three cases there are useful, and different, design reasons to adopt a private implementation scope:</p>  <p> </p>  <p>For RelativeDate, the Java implementation type int represents a coded Gregorian date value in the date scheme used by Crystal Reports. Not all int values correspond to valid dates, and the algorithm to map an int to a year/month/day equivalent is fairly complicated, taking into account things like Gregorian calendar reform. Thus, it is desirable to hide the implementation of this type.</p>  <p> </p>  <p>For StringNoCase, the implementation is more straightforward as a java.lang.String. The reason to adopt a private implementation scope is to ensure that all functions involving StringNoCase preserve the semantics of StringNoCase as representing a case-insensitive string value. Otherwise it is very easy for clients to declare a function such as:</p>  <p> </p>  <p><strong>foreign</strong> <strong>unsafe</strong> <strong>import</strong> <strong>jvm</strong> "method replace"</p>  <p>    replaceChar <strong>::</strong> StringNoCase <strong>-></strong> Char <strong>-></strong> Char <strong>-></strong> StringNoCase<strong>;</strong></p>  <p> </p>  <p>which does not handle case-insensitivity correctly, but is a perfectly valid declaration. This declaration results in a compilation error when it is placed outside the module in which StringNoCase is defined because of the private implementation scope of StringNoCase.</p>  <p> </p>  <p>For Color, the issue is somewhat more subtle. The java.awt.Color implementation type is semantically the same as the CAL Color type. The problem is that java.awt.Color is mutable (since it can be sub-classed to create a mutable type). It is preferable for a first-class CAL type to not be mutable, so we simply make the implementation scope private to ensure that this will be the case. </p>  <p> </p>  <p>A somewhat less encapsulated kind of abstract data type can be created using <em>friend modules </em>and <em>protected</em> scope. For example, if an algebraic type is public, and all its data constructors are protected, then the data constructors can be accessed in the friend modules of the module in which the type is defined. Effectively this means that the implementation of the semantics of the type stretches over the module in which the type is defined, and all of its friend modules. These must all be checked if the implementation of the type is modified. </p>  <p> </p>  <p>Given the merits of abstract data types discussed above, it is perhaps surprising that most of the core types defined in the Prelude module are not abstract data types. For example: Boolean, Char, Int, Double, String, List, Maybe, Either, Ordering, JObject, JList, and all record and tuple types are non-abstract types. </p>  <p> </p>  <p>There are different reasons for this, depending on the particular type involved. </p>  <p> </p>  <p>For example, Boolean, List, Maybe, Either and Ordering are all rather canonical algebraic data types with a long history in functional languages, with many standard functions using them. They are thus guaranteed never to change. In addition, their values have no particular design invariants that need to be enforced via constructor functions. Exposing the data constructors gives clients some additional syntactic flexibility in using values of the type. For example, they can pattern match on the values using case expressions or let patterns.</p>  <p> </p>  <p>Essentially the same explanation holds for record and tuple types. Although non-tuple record types are less canonical, they do correspond to the fundamental notion of an anonymous named-field product type. The "anonymous" here simply means that the programmer can create an entirely new record type simply by creating a value; the type does not have to be declared anywhere prior to use.</p>  <p> </p>  <p>Char, Int, Double, String, JObject and JList are foreign types where in fact part of the semantics of the type is that we want clients to know that the type is a foreign type. For example, we want clients to know that Prelude.Int is essentially the Java primitive unboxed int type, and has all the semantics you would expect of the Java int type i.e. this is quite different from RelativeDate which is using int as its implementation type in a very tactical way that we may choose to change. One can think of a public foreign type declaration with public implementation scope as simply introducing the Java type into the CAL namespace.</p>  <p> </p>  <p>One interesting point here is with CAL&#39;s naming convention for public foreign types. We prefix a type name by "J" (for "Java") for foreign types with public implementation type such that the underlying Java type is mutable. This is intended as mnemonic that the type is not a pure functional type and thus some caution needs to be taken when using it. For example, Prelude.JObject has public Java implementation type java.lang.Object.</p>  <p> </p>  <p>In the case where the underlying Java type is not mutable, we do not use the prefix, since even though the type is foreign; it is basically a first class functional type and can be freely used without concern. For example, Prelude.String has public Java implementation type java.lang.String.</p>  <p> </p>  <p>In the case where the implementation type is private, then the fact that the type is a foreign type, whether mutable or not, is an implementation detail and we do not hint at that detail via the name. Thus Color.Color has as its private Java implementation type the mutable Java type java.awt.Color. </p>  <p> </p>  <p>When creating abstract data types it is important to not inadvertently supply public API functions that conflict with the desired public semantics of the type. For example, if the type is publicly a pure-functional (i.e. immutable) type such as Color, it is important not to expose functions that mutate the internal Java representation.</p>  <p> </p>  <p>A more subtle case of inadvertently exposing the implementation of a type can occur with derived instances. For example, deriving the Prelude.Outputable and Prelude.Inputable type classes on a foreign type, whose implementation type is a mutable Java reference type, allows the client to gain access to the underlying Java value and mutate it
    (by calling Prelude.output, mutating, and then calling Prelude.input). The solution in this case is to not derive Inputable and Outputable instances, but rather to define a custom Inputable and Outputable instance that copies the underlying values.</p>

    Hi Pandra801,
    When you create a the external content type, please try to add a filter based on your select statement.
    http://arsalkhatri.wordpress.com/2012/01/07/external-list-with-bcs-search-filters-finders/
    Or, try to create a stored procedure based on your select statement, then create ECT using the SQL stored procedure.
    A step by step guide in designing BCS entities by using a SQL stored procedure
    http://blogs.msdn.com/b/sharepointdev/archive/2011/02/10/173-a-step-by-step-guide-in-designing-bcs-entities-by-using-a-sql-stored-procedure.aspx
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • I need to set up an expense form so that our consultant can "filter" by customer type, program type, and finally the purpose of the trip. For instance: the customer types are churches, schools, organizations. The program type would be fund raising, gift p

    I need to set up an expense form so that our consultant can "filter" by customer type, program type, and finally the purpose of the trip. For instance: the customer types are churches, schools, organizations. The program type would be dependent on the customer type selection from the first list. Some examples would be: fund raising, gift planning, surveys, and others. The purpose of the trip would be dependent on the program type selected from the second list. Some examples of trip purposes would be: presentation, design, prospecting. Further, the purpose of trip selection from the third drop-down box would then have to determine the values of other fields by expense type: such as commission, airfare, hotel. etc. I've tried pop-up menu but can't figure out how to "select" from the final popup list and have it populate a field for the purpose of the trip. I've tried to look at the JavaScript examples for dependent drop-down boxes, but can't find any that quite fit what I'm trying to accomplish. I am very new to all of this. No training in writing Javascripts - just trying to wing it. The form has to be very simple for our consultants to use, but also give our office the detail we need to process through the correct account numbers. I would appreciate any detailed step-by-step instructions - kind of a javascript for dummies type of info. HELP!

    An AcroForm is the name given to the type of PDF form that you create in Acrobat. An XFA form is the type of form that you create in LiveCycle Designer. Although they are both PDF files, they are very different structurally and have significant;y different scripting models. So pay attention to the information on AcroForms and ignore anything about XFA. Be sure to get the sample PDF forms so you can look at how it works and where the scripts are placed.
    What you want to do will require scripting, and if you don't have the experience and are unable to use the information in the tutorials to create what you want, you might consider getting someone who has experience do this for you. I'll often suggest code if I can do so quickly, but what you want requires more than a few minutes.

Maybe you are looking for