To get Class object representing the primitive type by a String

for classes,I can use
classNameString = "java.lang.String"
Class c=Class.forName(classNameString);
to get Class object representing the classNameString.
but to get Class object representing the primitive type ,I have to use something like :
Class c=Integer.TYPE;
is there any way to get Class object representing the primitive type by a String?

not using Class.forName(). you'll just need to key off the String passed to see whether it names a primitive:class ClassUtilities {
   * Gives the <code>Class</code> corresponding to a named class or primitive.
   * @param  name  FQN of a class, or the name of a primitive type
   * @param  loader  a {@link java.lang.ClassLoader ClassLoader}
   * @return  the <code>Class</code> for the name given.  This method
   * converts primitive type names to their particular <code>Class</code>
   * object.  <code>null</code>, the empty string, <code>"null"</code>, and
   * <code>"void"</code> yield {@link java.lang.Void#TYPE Void.TYPE}.  If any
   * classes require loading because of this operation, the given
   * <code>ClassLoader</code> performs the loading.  Such classes are not
   * initialized, however.
   * @throws  ClassNotFoundException  if the name names an unknown class
   * or primitive
   * @see  java.lang.Class#getName
  static Class classForNameOrPrimitive( String name, ClassLoader loader )
    throws ClassNotFoundException {
    if ( name == null || name.equals( "" ) || name.equals( "null" ) || name.equals( "void" ) ) {
      return Void.TYPE;
    if ( name.equals( "boolean" ) )
      return Boolean.TYPE;
    if ( name.equals( "byte" ) )
      return Byte.TYPE;
    if ( name.equals( "char" ) )
      return Character.TYPE;
    if ( name.equals( "double" ) )
      return Double.TYPE;
    if ( name.equals( "float" ) )
      return Float.TYPE;
    if ( name.equals( "int" ) )
      return Integer.TYPE;
    if ( name.equals( "long" ) )
      return Long.TYPE;
    if ( name.equals( "short" ) )
      return Short.TYPE;
    return Class.forName( name, false, loader );
}

Similar Messages

  • How to use the substring and can i class method for the primitive type

    MY COMPILER
    public class StringLine
    public static void main(String[] args)
    String sentence;
    char letter;
    char name;
    int position;
    System.out.println("Enter a line of text. No punctuation please");
    sentence = MyIO.readLine();
    System.out.println("I have rephrase that line to read:");
    position = sentence.indexOf(" ");
    name = sentence.charAt(postion, position+ 1);
    name = name.toUpperCase();
    letter = sentence.charAt(0);
    letter = letter.toLowerCase();
    sentence = name + sentence.substring(position + 2)
              + letter + sentence.substring(1, position);
    //////////////// I got 3 errors following:
    StringLine.java:16: cannot resolve symbol
    symbol : variable postion
    location: class StringLine
    name = sentence.charAt(postion, position+ 1);
    ^
    StringLine.java:17: char cannot be dereferenced
    name = name.toUpperCase();
    ^
    StringLine.java:20: char cannot be dereferenced
    letter = letter.toLowerCase();
    ^
    3 errors
    }

    position = sentence.indexOf(" ");
    name = sentence.charAt(postion, position+ 1);
    name = name.toUpperCase(); two error here:
    1. as stated above postion is mispelled...should be position
    2. you cannot perform a chatAT(int, int)
    I think you want to perform a substring
    String name;  // should be a string instead of a char..(char is a primitive and all primitive have no method)
    position = sentence.indexOf(" ");  
    name = sentence.substring(position, position + 1).toUpperCase();
    [./code]
    better yet..you should check if the sentence does contain a spaceString name;
    position = sentence.indexOf(" "); // return a negative value if the search string is not part of the string
    if (position != -1)
    name = sentence.substring(position, position + 1).toUpperCase();
    else
    System.out.println("The sentence does not contain a space);
    [./code]
    String letter;
    letter = new String(sentence.charAt(0));
    letter = letter.toLowerCase();
    // or
    char letter;
    letter = sentence.toLowercase().charAt(0);

  • Create array of arbitrary dimensions / get Class object for primitive types

    Here's an interesting problem: is there any way to code for the creation of an n-dimensional array where n is only known at runtime (input by user, etc.)?
    java.lang.reflect.Array has a newInstance method which returns an array of an arbitrary number of dimensions specified by the int[] argument, which would give me what I want. However, the other argument is a Class object representing the component type of the array. If you want to use this method to get an array of a primitive type, is it possible to get a Class object representing a primitive type?

    That doesn't help, since the whole problem is that the number of dimensions aren't known until runtime. You can't simply declare a variable of type int[][] or use an int[][] cast, since the number of []'s is variable.
    The int.class construction was partly what I was looking for. This returns the array needed (assuming some read method):
    int dimensions = read();
    int size = read();
    int[] index = new int[dimensions];
    for (int i = 0; i < dimensions; i++)
        index[i] = size;
    Object myArray = Array.newInstance(int.class, index);The only problem is, as an Object, I can't use myArray usefully as an array. And I can't use a cast, since that requires a fixed number of dimensions.

  • While running my app I get the below error  - have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature

    I am running ATG[10.1.2] app on Jboss [EAP 5.1.0 GA] I am able to open dyn/admin however when I start my app I get the below error
    java.lang.LinkageError: loader constraint violation: when resolving method "atg.servlet.ServletUtil.setSessionConfNumCacheRequest(Ljavax/servlet/http/HttpServletRequest;)Ljavax/servlet/http/HttpServletRequest;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, atg/filter/dspjsp/PageFilter, and the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) for resolved class, atg/servlet/ServletUtil, have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature
      at atg.filter.dspjsp.PageFilter.doFilter(PageFilter.java:215)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ForwardFilter.doFilter(ForwardFilter.java:263)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ErrorFilter.doFilter(ErrorFilter.java:279)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:638)
      at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:446)
      at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
      at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
      at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:416)
      at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
      at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:286)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
      at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
      at java.lang.Thread.run(Thread.java:680)
    11:22:47,413 ERROR [[localhost]] Exception Processing ErrorPage[errorCode=500, location=/global/errorPage500.jsp]

    The supported JBoss version for 10.1.2 is JBoss EAP 5.1.2 but I don't think that your issue is caused because of this. Your issue is more of an environmental thing as you are probably getting two different versions getting loaded of class javax.servlet.http.HttpServletRequest and so correspondingly two different Class objects as the error shows. One reason for this could be if you include any server-specific libraries (in present case the Servlet API JAR which contains the class javax.servlet.http.HttpServletRequest) of a different version in the /WEB-INF/lib of your web application. Try removing it from there if so and see if that helps.

  • How can i add custom attributes to a new Class Object using the API ?

    Hello everyone,
    Here is my problem. I just created a subclass of Document using the API (not XML), by creating a ClassObjectDefinition and a ClassObject. Here is the code :
    // doc is an instance of Document
    ClassObject co = doc.getClassObject();
    ClassObjectDefinition cod = new ClassObjectDefinition(ifsSession);
    cod.setSuperclass(co);
    cod.setSuperclassName(co.getName());
    cod.setName("MYDocument");
    ClassObject c = (ClassObject)ifsSession.createSchemaObject(cod);
    Everything seems to be OK since i can see the new class when i use ifsmgr. But my question is : how can i add custom attributes to this new class ? Here is what i tried :
    AttributeDefinition value = new AttributeDefinition(ifsSession);
    value.setAttribute("FOO", AttributeValue.newAttributeValue("bar"));
    c.addAttribute(value);
    But i got the following error message :
    oracle.ifs.common.IfsException: IFS-30002: Unable to create new LibraryObject
    java.sql.SQLException: ORA-01400: impossible d'insirer NULL dans ("IFSSYS"."ODM_ATTRIBUTE"."DATATYPE")
    oracle.ifs.server.S_LibraryObjectData oracle.ifs.beans.LibrarySession.DMNewSchemaObject(oracle.ifs.server.S_LibraryObjectDefinition)
    oracle.ifs.beans.SchemaObject oracle.ifs.beans.LibrarySession.NewSchemaObject(oracle.ifs.beans.SchemaObjectDefinition)
    oracle.ifs.beans.SchemaObject oracle.ifs.beans.LibrarySession.createSchemaObject(oracle.ifs.beans.SchemaObjectDefinition)
    void fr.sword.ifs.GestionDocument.IFSDocument.createDocument(java.lang.String)
    void fr.sword.ifs.GestionDocument.IFSDocument.main(java.lang.String[])
    So, what am i doing wrong ?
    More generally, are we restricted in the types of the attributes ? (for example, would it be possible to add an attribute that would be an inputStream ? Or an object that i have already created ?).
    Any help would be appreciated. Thanks in advance.
    Guillaume
    PS : i'm using Oracle iFS 1.1.9 on NT4 SP6 and Oracle 8.1.7
    null

    Hi Guillaume,
    you're welcome. Don't know exactly, but assume that ATTRIBUTEDATATYPE_UNKNOWN
    is used to check for erronous cases only
    and it shouldn't be used otherwise.
    Creating your own objects could be simply done via
    ClassObject ifsClassObject;
    DocumentDefinition ifsDocDef = new DocumentDefinition(ifsSession);
    // get class object for my very own document
    ifsClassObject = ClassObject.getClassObjectFromLabel(ifsSession, "MYDOCUMENT");
    // set the class for the document i'd like to create
    ifsDocDef.setClassObject(ifsClassObject);
    // set attributes and content for the document...
    ifsDocDef.setAttribute("MYFOO_ATTRIBUTE",....);
    ifsDocDef.setContent("This is the content of my document");
    // create the document...
    PublicObject doc = ifsSession.createPublicObject(ifsDocDef);
    null

  • EEWB :  how to determine the business object and the extension type ?

    Hi,
    I ask myself how to determine the business object and the extension type to use to add new fields in a new tab of a specific transaction ? what means each business object, does that correspond to a specific transaction ?
    I need to add a new tab in the ‘BaMI’ business activity in transaction CRMD_ORDER just after the tab 'Actions' at header level.
    Could you help me please to determine which business object and extension type I have to select during creation of the project and which business object category I have to select during creation of the extension (wizard) ?
    Thanks for your help,
    Marie

    Marie,
    In order to determine what type of transaction you are extending, you will need to look at the customizing for the transaction.
    In the IMG:
    Goto:
    Customer Relationship Management->Transactions->Basic Settings->Define Transaction Types.
    You will then choose the transaction defined that you want to extend.  If you display the details of the transaction you will find an attribute called:
    "Leading Transaction Category".  This tells you the general context in which the transaction is used.  The other item to view is the assignment of business transaction categories found in the maintenance screen.
    This information general corresponds to one of the options that the EEWB will give you on the transaction type.
    As far as extensions go, my recommendation is the following:
    - Use CUSTOMER_H Customer Header Extensions for any new fields at the header level.
    - Use CUSTOMER_I Customer Item Extensions for any new fields at the item level.
    Unless you have a specific requirement to extend a segment of the transaction, I recommend placing all new fields in these segments.  The CUSTOMER_H & CUSTOMER_I segments are considered "standard" segments, that are already built into all the necessary API structures. 
    Let me know if you have any further questions.
    Good luck,
    Stephen

  • Cannot invoke toString on the primitive type int

    im trying to make a sudoku puzzle but having trouble with the arrays, ive got two arrays
    int [][] actual = new int [9][9];
        String [][] possible = new String [9][9];part of my code im trying to generate a sudoku board, this is the part of the error in
    public void possVals(int col, int row)
              if(possible[col][row].equals(""))
                   str = "123456789";
              else str = possible[col][row];
              for(r = 1; r < 9; r++)
                   if(actual[col][r] != 0)
                        str = str.Replace(actual[col][r].toString(), "");
              }could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' please

    ajp_08 wrote:
    could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' pleaseBut you can do like this
    int i = 12345;
    String s = Integer.toString(12345);So, the following should work
    str = str.Replace(Integer.toString(actual[col][r]), "");Good luck!
    Edited by: A.J.Bharanidharan on Nov 17, 2009 6:06 PM

  • Why can't created an object in the "public static void main(String args[])"

    Example:
    public Class Exp {
    public static void main(String args[])
    new Exp2();-------------> To Occur Error
    Class Exp2 {
    public Exp2()

    You can't create an inner class within main, because
    it is a static method. Inner classes can only be
    created by true class methods.This is not correct. You can create an inner class object in a static method. You just have to specify an outer class object that the inner class object should be created within:
    Exp2 exp2 = new Exp().new Exp2();

  • Get class object for primitive datatype name stored in a string

    Hi,
    I have an array of Strings:
    String[] somePrimitives = {"int", "char", "void" };
    I want to achieve the equivalent of :
    for(int k = 0; k < somePrimitives.length; k++) {
    Class myClass = Class.forName(somePrimitives[k]); //Wont work
    We all know, we cannot do Class.forName("int") etc since "int" is not a path to
    an actual class - whereas Class.forName("java.lang.Integer") will work.
    Can anyone tell me how to achieve the above ?
    Of course, I don't want to have numerous hardcoded checking conditions like
    if(somePrimitives[k].equals("int")) return (Integer.TYPE);
    thanks.

    1. Why couldn't java provide me a simple provision to list all available primitives and their corresponding
    class mapping ? Why should I do the mapping...shouldn't the language have taken care of
    its provisions ?Yes, and native compilation on the fly, dynamic modification of classes, a sensible types system, usable Number tree, quasiquotation, access to the AST of the source, getting a method based on argument types rather than parameter types, etc. etc.
    2. Or even better they could have made the method
    Class.getPrimitiveClass(String primitiveDatatTypeName)
    as a public method. This would have solved the whole
    problem with a one line piece of code. Why did they
    have to make it non-public ???If you want it easy, go elsewhere.
    But seriously, the reflection capabilities were tagged onto Java as it grew, and were not designed to reflect the state of the art, but as a 'just enough to get by' solution. Most of the time people don't need it, so it's not there, any you have to roll your own.
    Pete

  • Keeps finding a "Object" not the real type.. I am really lost.. :D

    The calls to other objects work fine, I have testing all of them.. but! when I compile I get a error about finding a "object" type and not a String type at
    for(String blackStone : blackUnits.keySet())
                   if( getSetLib(blackStone) == 0 ) { removeSet.add(blackStone); }
             }   this is the whole class
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Set;
    public class Stat
        private Token[][] board;
        private int bSize;
        private HashMap<String, HashSet> unitsWhite;
        private HashMap<String, HashSet> unitsBlack;
        double last;
        public Stat(Token[][] goBoard, int size)
            board = goBoard;
            bSize = size;
            unitsWhite = new HashMap< String , HashSet>();
            unitsBlack = new HashMap< String , HashSet>();
            last = bSize -1;
         * Delimiter is /
        public HashSet getLib(int x , int y)
            HashSet liberties = new HashSet<String>();
            //error catch
            if(board[x][y] == null){return liberties;}
            int tempX = x;
            int tempY = y;
            //error catch for out of rage if size ect..
            for(int i = 0 , liby = y ,libx = x ; i <= 3; i++)
                if(i == 0){libx = -1; liby = 0;}
                if(i == 1){libx = 0; liby = -1;}
                if(i == 2){libx = 1; liby = 0;}
                if(i == 3){libx = 0; liby = 1;}
                tempX = x+libx;
                tempY = y+liby;
                if(tempX >= 0 || tempY >= 0)
                    if( tempX <= last || tempY <= last )   
                         if( (tempX < 0 || tempY < 0) || ( tempX >= last || tempY >= last ) )
                           tempX = 0;
                           tempY = 0;
                         else
                            if( board[tempX][tempY] == null) { liberties.add(tempX+"/"+tempY); }
            return liberties;  
        public void getTer()
        public void checkForCaptured()
            Token black = null;
            Token white = null;
            HashMap blackUnits;
            HashMap whiteUnits; 
            HashSet removeSet ;
            removeSet = new HashSet<String>();
            //look for a Token on the board and if you find one look for any dead  Tokens
            //looks for a Token
            for(int x=0; x < bSize;x++)
              { for(int y=0 ; y < bSize   ;y++)
               { if(board[x][y] != null)
                   if (black == null)if( board[x][y].getColor().equals("black") ) black =  board[y][x];
                   if (white == null)if( board[x][y].getColor().equals("white") ) white =  board[y][x];
            System.out.println("this is black tokens color" +black.getColor());
            //looks for a dead unit
            if(black != null)
             { blackUnits = black.getUnits();
               System.out.println("black :" +blackUnits.keySet().size() ) ;
               for(String blackStone : blackUnits.keySet())
                   if( getSetLib(blackStone) == 0 ) { removeSet.add(blackStone); }
            if(white != null)
            { whiteUnits = white.getUnits();
                System.out.println(" white: "+whiteUnits.keySet().size() );
              for( String whiteStone : whiteUnits.keySet() )
               { if( getSetLib(whiteStone) == 0 ) { removeSet.add(whiteStone); } }
            board.removeUnitsSet(removeSet);    
         public int getSetLib(HashSet Units)
             return 0;
    }someone point me in the correct direction PLZ! I don't mind RTFM if you give me a FM and page/line to look at.
    THANKS!
    Message was edited by:
    monji112000

    The compiler doesn't know that you're only putting Strings in as keys. HashMap takes references to Object as keys and hence returns references to Object in keySet(). Note, however, that the object itself is still what you put in there. But the compiler only has the declared return type of the method to look at.
    // pre 1.5
    for (Iterator iter = set.iterator(); iter.hasNext();) {
        String key = (String)iter.next(); // cast Object to String. Only works if you actually put a String in
        // do stuff with key
    // 1.5, if you don't use generics
    for (Object obj : set) {
        String key = (String)obj;
        // do stuff with key
    // 1.5, with generics
    Set<String> set = ...;
    for (String key : set) {
        // do stuff with key
    }Since you have a Map, you'll have Map<String, SomeValueType>.
    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
    http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

  • How to get CLASS name for the generic item?

    Hi,
    I wrote following method to create a service instance.
    public static <IType> IType GetServiceInstance()
           IType type=null;
            try
            InitialContext ic=new InitialContext();
    //ERROR:      type=   ic.lookup(IType.class.getName());
            catch(Exception ex)
            //do handle
            return type;
        }please see the //Error: here its giving error, also i m not getting "class" variable in IDE!!!
    i want use like this;
    IUserService userService=ServiceFactory.GetServiceInstance<IUserService>();so how can i do this?
    Edited by: Manikandan.Java on Oct 31, 2007 3:02 AM

    I don't know if I understand your question, but you cannot find the class name because it is in run time just an object. You can, however, check if it is an instanceof.
    if (genericType instanceof MyType) {
         doMyThing();
    }

  • Can I create a Class object without the VM?

    Using byte-code engineering, is it possible to create a class object?
    What about if I serialize a Class object to a file, can I byte-code engineer that and then reinstantiate it?

    Thanks I'll check it out. Basically I want to try it
    for fixing a problem of running two apps in the same
    VM.There's a world of problems when you try to run two programs within the same JVM. I wouldn't suggest even trying it unless it's a last resort. Why do you want to do that?

  • Error - && operator is undefined for the arugument type java,lagn.string

    Hi All
    I am new to this forum and also java .
    Below is my program
    Please let me know the fix for this error
    Thanks
    Guna
    The Logic is , I want to check the customer first,last and middle name .
    Senario 1 : I want to check the customer name if he gives only FIRST NAME
    Senario 2 : I want to check the customer name if he gives only LAST NAME
    Senario 3 : I want to check the customer name if he gives only MIDDLE NAME
    Senario 4 : I want to check the customer name if he gives First name and last name - this wher i get my error
    My Coding
    package SelfLearning;
    import java.util.*;
    public class CustomerUtil {
         boolean SearchCustomer(List<Customer> listObj , Customer cust )
              Iterator listOfCustomerObj = listObj.iterator();
              Customer cust1 = null ;
              while(listOfCustomerObj.hasNext())
                   cust1 = (Customer) listOfCustomerObj.next();
              if(cust1.getFirstName().equalsIgnoreCase(cust.getFirstName()))
                   System.out.println("Customer Found");
              if(cust1.getLastName().equalsIgnoreCase(cust.getLastName()))
                   System.out.println("Customer Found");     
    // I am getting error here , How to fix this error . please let me know is there any another want to rewrite this condition.
              if(cust1.getFirstName()&& cust1.getLastName().equalsIgnoreCase(cust.getFirstName()&& cust.getLastName())
                   System.out.println("Customer Found");
              return true ;
    }

    Folks
    I am new to this forum and also to java .
    I will post the whole coding.
    I did try putting the code tag but its not working . Sorry
    I saw the link but I cant do it .
    Below is my coding
    {code }
    package SelfLearning;
    public class Customer {
         String firstName;
         String LastName;
         String MiddleName;
         public Customer() {
         public Customer(String firstName, String lastName, String middleName) {
              super();
              this.firstName = firstName;
              LastName = lastName;
              MiddleName = middleName;
         public String getFirstName() {
              return firstName;
         public void setFirstName(String firstName) {
              this.firstName = firstName;
         public String getLastName() {
              return LastName;
         public void setLastName(String lastName) {
              LastName = lastName;
         public String getMiddleName() {
              return MiddleName;
         public void setMiddleName(String middleName) {
              MiddleName = middleName;
    package SelfLearning;
    import java.util.*;
    public class CustomerUtil {
         boolean SearchCustomer(List<Customer> listObj , Customer cust )
              Iterator listOfCustomerObj = listObj.iterator();
              Customer cust1 = null ;
              while(listOfCustomerObj.hasNext())
                   cust1 = (Customer) listOfCustomerObj.next();
              if(cust1.getFirstName().equalsIgnoreCase(cust.getFirstName()))
                   System.out.println("Customer Found");
              if(cust1.getLastName().equalsIgnoreCase(cust.getLastName()))
                   System.out.println("Customer Found");     
    // Here I want to check both first and last name . But Some how I am unable to do it .
              if((cust1.getFirstName()+cust1.getLastName().equalsIgnoreCase(custObj4.getFirstName()+(custObj4.getLastName()))
                   System.out.println("Customer Found");
              return true ;
    package SelfLearning;
    import java.util.ArrayList;
    import java.util.List;
    public class TestCustomer {
         * @param args
         public static void main(String[] args) {
              Customer custObj1 = new Customer("John" , "Lee ", "jayson");
              Customer custObj2 = new Customer("Matt" , "G ", "C");
              Customer custObj3 = new Customer("Bob" , "George ", "K");
              List customerDetails = new ArrayList();
              Customer custObj4 = new Customer();
              custObj4.setFirstName("Kela");
              custObj4.setMiddleName("v");
              customerDetails.add(custObj1);
              customerDetails.add(custObj2);
              customerDetails.add(custObj3);
              CustomerUtil custUtil = new CustomerUtil();
              custUtil.SearchCustomer(customerDetails , custObj4);
    Edited by: Guna on Apr 7, 2011 11:59 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to get a Class object with a generic type of list

    Hi,
    I want to get an instance of a class which is of type List<ABC>. How can I get that ?
    What I tried was Class c = List<ABC>.class , bu this is not compiling. I can get new ArrayList<ABC>().getClass() , but the type of that class would be Class<? extends ArrayList<ABC>> but not what I want Class<? extends List<ABC>> ...
    Thanks in Advance.
    Bhargava

    Thanks for so many responses. I understand that you can not get a class instance of type Class<List<E>>. Am I correct?
    My use case was something like this:
    Class X implements Y<SrcType, DescType> {
      public DestType transform(SrcType src) { ---- }
    }Now I want to write a factory which maintains a list of implemenrations of interface Y in a map. For e.g. {List(SrcType,DestType) -> X}. This factory provides one method with the following signature:
    Class Yfactory {
       public Y transform(SrcType o, Class destType) {
        //This figures out which transformer to apply based on SrcType and destType and gives it back.
    }Now, there is one case where a transformer transforms from type A to List<B> (X implements Y<A, List<B>>) . How should I add it to the map in factory and how do I call the factory's transform method so that it choose this transformer?

  • 2d object with multiple primitive types

    I've done some research and tried a few options and finally decided that I want a two dimensional object to handle several different types of primitives. My current plan is to just put them all in a 2d String array, then parse them to whatever type I need when I need to do calculations with the integers or doubles. But I also wanted to ask if there was already an object type that could handle this for me without the parsing. I need more than one value per key, so I don't think that a map will work (although I've admittedly never used one before and may not fully understand how it operates).
    My other thought was to just make a new object with several different arrays of different types and to use the indices to relate one to another. This would at least clean up my code and take out some repetitive parsing steps, but it seems a very roundabout way to handle the situation.
    Any suggestions?
    Should I just use a 2d String array?
    Should I make a new object?
    Does an object already exist for this application?
    Also, if I muddied any of this up by using improper word choice, please let me know so that I can try to clarify.

    Fair enough. I'm working on analyzing some data for a videogame. I want to find the optimal set of items on a character by trying every combination and analyzing it's effectiveness. In order to do this, I want to store about a dozen different stats (some integers, some doubles) for about 30 different items along with the item's name, then use some nested loops to evaluate each combination. There is no 'perfect answer', so I need to perform this process multiple times under varying circumstances. I figure this would be easiest to accomplish if every stat is associated with an x value and every item is associated with a y value because I could then use the index of a for loop to process the information.
    In short, I have several different data types that I want to store in a manner that allows me to load and retrieve all the information using loops. Each set of data has the exact same format (String, int, int, double, double, double...).
    I know it doesn't sound like an important project, but I like to take any opportunity I can to practice my programming. I think it's an important skill in today's world and I'm always trying to improve.

Maybe you are looking for