Compiler error  type of object in for (Class obj : Items) - why?

Hi all,
I'm new to Java generics and am in the process of converting some
legacy code. I have encountered a particular error which I do not
understand the reason for, since I think the compiler has enough
information about the code to work out type information. The following
code shows a test class which demonstrates this error:
import java.util.Collection;
public class Test
    interface Base {}
    static class Impl1 implements Base{}
    public <T extends Base> Collection<T> getCollection(Class<? extends Base> cls)
        return null;
    void someMethod()
        for ( Impl1 obj : getCollection( Impl1.class ))
            // *** compiler complains about the line above ***
            // compiler says:
            // Test.java:22: incompatible types
            // found   : Test.Base
            // required: Test.Impl1
            //        for ( Impl1 obj : getCollection( Impl1.class ))
            //                                        ^
    void someMethod2()
        Collection<Impl1> coln = getCollection(Impl1.class);
        for (Impl1 obj : coln)
            // do something here with obj
}Why should the compiler complain where it does ( the line marked with
asterisks) in someMethod, but does not reject the declaration statement
in someMethod2? I would have assumed both are the same and the
compiler has the same type information at its disposal to determine
the correct type.
Cheers,
Bonny

The Java 5 compiler not only looks at a method's name and arguments, but also at its return value in order to determine whether a method is callable and what type should be infered for its type parameters.
In your example the type parameter T is only used in the declaration of the method's return type. Note that there is no relation between T and the type of the argument cls!
Thus, the compiles needs to know what type of variable the return value will be assigned to.
Hence, someMethod2 can be resolved, whereas in someMethod there is no assignment of the return value. (Rather, an implicit call to Iterable.iterator()).
You can solve this problem by forming a relation between the method's argument, its return type and its type parameter. Just declare the method like this:
public <T extends Base> Collection<T> getCollection(Class<T> cls)
        return null;
    }

Similar Messages

  • ERROR - JBO-25005: Object name  for type View Object is invalid

    Hi All,
    I am getting this error "JBO-25005: Object name for type View Object is invalid" while executing my VO query in Controller code. Can any one please tell me the reason behind this error?
    I am creating a VO dynamically and .xml file of a VO is placed in a proper directly. Please let me know some inputs to resolve this.
    Thanks & Regards,
    -Abm

    I found the below explanation for the error mentioned. Check if your package name, Object names confirm to the standard specified
    JBO-25005: InvalidObjNameException
    Cause: An attempt has been made to associate a business component name with an object for which it is not valid.
    Action: The name should be a valid Java identifier with no spaces or punctuation. Names are of the format myProjectPackage.BusinessPackage.BusinessComponent

  • Serialization error: no serializer is registered for class BasicDynaBean

    Hi,
    I have created webservice for the java class i have written. And i was also successful in deploying the webservice on the application server.
    when i was trying to test the webservice, few of the operations were working fine. But i came across such kind of error message when i am trying to invoke one of the methods i have written . Below is the following error message seen from SOAP respone, highlighted with bold.
    <?xml version="1.0" encoding="UTF-8"?>
    <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://dataaccess/types/" xmlns:ns1="http://www.oracle.com/webservices/internal/literal"><env:Body><env:Fault><faultcode>env:Server</faultcode>
    <faultstring>Internal Server Error (serialization error: no serializer is registered for (class org.apache.commons.beanutils.BasicDynaBean, null))</faultstring></env:Fault></env:Body></env:Envelope>
    I am using RowSetDynaClass for representing the results of an SQL query.
    Please let me know if any one could provide me a solution for this error.
    Thanks.

    Hi,
    I have created webservice for the java class i have written. And i was also successful in deploying the webservice on the application server.
    when i was trying to test the webservice, few of the operations were working fine. But i came across such kind of error message when i am trying to invoke one of the methods i have written . Below is the following error message seen from SOAP respone, highlighted with bold.
    <?xml version="1.0" encoding="UTF-8"?>
    <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://dataaccess/types/" xmlns:ns1="http://www.oracle.com/webservices/internal/literal"><env:Body><env:Fault><faultcode>env:Server</faultcode>
    <faultstring>Internal Server Error (serialization error: no serializer is registered for (class org.apache.commons.beanutils.BasicDynaBean, null))</faultstring></env:Fault></env:Body></env:Envelope>
    I am using RowSetDynaClass for representing the results of an SQL query.
    Please let me know if any one could provide me a solution for this error.
    Thanks.

  • Compiling error in my test file for Reader class.

    I did a small program trying to test Reader class, here is my code:
    package testfilereader;
    import java.io.*;
    import java.io.Reader;
    import java.io.InputStream;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2001
    * Company:
    * @author
    * @version 1.0
    public class FileTest {
    public static void main(String args[]){
    Byte buff[] = new Byte[80];
    try{
    InputStream r = new FileInputStream("test.txt");
    int i = r.read(buff);
    String s = new String(buff);
    System.out.println(s);
    }catch(NullPointerException e){}
    catch(IOException e2){}
    But I continue to get compiling errors:
    C:\>javac FileTest.java
    FileTest.java:19: cannot resolve symbol
    symbol : method read (java.lang.Byte[])
    location: class java.io.InputStream
    int i = r.read(buff);
    ^
    FileTest.java:20: cannot resolve symbol
    symbol : constructor String (java.lang.Byte[])
    location: class java.lang.String
    String s = new String(buff);
    Please advise what is wrong here.

    Replace Byte with byte - the methods
    expect arrays of byte; not Byte (which is a simple
    class wrapper for byte).Hi, I changed to:
    byte buff[] = new byte[80];
    Same errors, any other ideas?

  • After December 2014 update, Compile Error - calling Excel Objects Sub "Object library invalid or contains references to object definitions that could not be found"

    When try to call Sub in Excel Objects > SheetXX after the original xlsm is modified and saved by another user in diff machine, getting an error below and seems Excel cannot identify any subs exists in Sheet.
    Compile error:
    Object library invalid or contains references to object definitions that could not be found
    Note: it seems that this problem has been occurring After December 2014 update and still exists even after applying the fix:
    http://blogs.technet.com/b/the_microsoft_excel_support_team_blog/archive/2014/12/11/forms-controls-stop-working-after-december-2014-updates-.aspx)

    Hi Kwlee324,
    Thanks for sharing the workaround with us. It would be very helpful for others who have the same issue.
    Also I found a two useful links about the error message "Object library invalid or contains references to object definitions that could not be found":
    https://support.microsoft.com/kb/2703186
    http://blogs.msdn.com/b/vsod/archive/2009/06/05/visual-basic-6-controls-stop-working-after-security-advisory-960715.aspx
    Hope it is helpful.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Compilation error- xws-security sample aplication for signing

    hi
    I tried to run the sample application (xws-security) in JWSDP 1.6 but i am getting the following error.
    [echo] Running wscompile....
    [wscompile] C:\Sun\jwsdp-2.0\xws-security\samples\simple\build\server\WEB-INF\c
    asses\simple\PingService.java:10: cannot access java.lang.Object
    [wscompile] bad class file: C:\Sun\AppServer\jdk\jre\lib\rt.jar(java/lang/Objec
    .class)
    [wscompile] class file has wrong version 49.0, should be 48.0
    [wscompile] Please remove or make sure it appears in the correct subdirectory o
    the classpath.
    [wscompile] public interface PingService extends javax.xml.rpc.Service {
    [wscompile] ^
    [wscompile] 1 error
    [wscompile] error: compilation failed, errors should have been reported

    it worked ....thank you ghstark

  • FM Error: No assignment object determined for P100 / 457000

    Dear GURUS,
    we are facing the problem while changing the PO and system is giving the error message as CB item 00010: No assignment object determined for P100 / 457000
    we checked in FM9K and reconstructed in FMBV and run the report .
    pl suggest...
    Message no. BP748
    Diagnosis
    The budget structure for the combination funds center P100/commitment item 457000/fund  in line item 00010 does not contain a superior assignment object in the commitment budget.
    Also, if you have only assigned one assignment object in the commitment budget, you must create assignment objects in such a way that every assignable element has ONE assignment object in the upward path in the commitment budget.
    System Response
    Posting not made.
    Procedure
    1. Define a superior element in the budget structure or define the BS element itself as an assignment object in the commitment budget.
    2. Check your definition.
    3. Reconstruct the assigned values for the fund and year where you have changed the assignment object definition.
    Regards,
    Venkat

    Hi,
    Please check the Note 1080301
    Summary
    Symptom
    You receive the error message BP746 or any similar message (see below).
    Other terms
    BP 746 - BP746 - BP 747 - BP747 - BP745 - BP 745 - BP748 - BP 748
    Reason and Prerequisites
    You use the functionality of assignment objects in the budget structure for Former Budgeting
    Solution
    The functionality of the assignment object is not generally released for customers.
    Customers who want to use this functionality must first contact SAP consulting, if they are allowed to do so.
    If you do not need or know this functionality, then you must update the budget structure (transaction code FM9K) and remove the definition of all assignment objects. Sometimes, the corresponding columns are hidden in the transactions FM9L or FM9K. If this is the case, you should first activate them in the table control settings (right-upper button). The columns in FM9K and FM9L have the titles "CmA" and "PmA".
    If you use a complex budget structure, the easiest way to detect these assignment objects will to search in table BPCJ for entries with the field WRTTP equal to 72 or 46. As well you can use table BPCK which tells you whether assignment objects are used or not, by filtering entries with the field WRTTP equal to 72 or 46.
    After removing all combinations detected in tables BPCJ or BPCK using transaction code FM9K, you must reconstruct availability control, by means of transaction code FMBV.
    Note
    Problems with assignment objects are detected by the report BPCARRC0.
    Thanks & Regards,
    Shashi Kanth.

  • I am able to compile a java file in eclipse inspite of compilation errors shown in eclipse and a .class file is generated

    Hi,
    I had a java file with compilation errors as shown in eclipse IDE.
    But the class file is still generated in the classes folder on building and pressing clean the project.
    I confirmed that the class file has an updated time stamp and also that a System.out.println() statement that i added was indeed printed out when this class was encountered during the running of a web application in which this class was called somewhere.
    (The java class has no subclasses and it is a single class with public modifier).
    How does it happen so?
    Regards,
    Karthik.

    As far as I know, the java code is compiled in Eclipse as soon as you save it. i.e. press CTRL+SHIFT+s
    as far as the build is concerned, in case you have a build file where you specify how to make a jar file, the location the jsr file is to be placed, only then you have to build the project. However again, as far as just simple compile is concerned as soon as you save the files are compiled. And show you the errors if any in the tasks window.

  • Compile error when using Collections.sort for Vector, why?

    The compiler is giving an error when trying to do this (I'm using JDK 1.5.0_09):
    Vector <String> test = new Vector <String>();
    test.add("test1");
    test.add("test2");
    test.add("test3");
    Collections.sort(test);The error being:
    The method sort(Vector<String>) is undefined for the type Collections
    Collections.sort takes List, but Vector is of type List, so this should work, correct?

    ChuckBing wrote:
    No. Vector is not a subclass of List. Use List.um.. Vector implements List

  • Java Core Program :: Dynamic Object Creation for Classe & Invoking the same

    Hi,
    I need to create a dynamic object for a class & invoke it.
    For eg: I have a table in my DB where all the names of my java classes are stored. I need to call name from the table of the DB and call that class dynamically in my java program.
    ResultSet_01 = executeQuery("select classname from class_table where class_descrip = 'Sales Invoice' ");
                   while(ResultSet_01.next())
                        String class_name = ResultSet_01.getDouble("classname");
                   }Now using the string in class_name that is fetched from ResultSet_01, I need to create an object for the class_name & invoke the class that is been created with the same name.
    Thank in advance.
    Regards,
    Haider Imani

    Well for a start since a class name is a String, not a number you'd better start by getting the name with getString() not getDouble().
    You need to work with fully qualified names, (FQNs) like "com.acme.myproject.MyDynamicClass", not just the bare MyDynamicClass.
    The next question is where the .class files for the dynamically loaded classes are stored. If they are part of your normal program code, on the class path, then you can use Class.forName to load the class and return a Class object. If they are in some special place you'll need to create a URLClassLoader and get the Class from that.
    Generally, when you load a class this way, it should implement some known interface, or extend some know abstract class. By placing objects of the dynamic class in a reference to that interface you can use the methods defined in the interface.
    The usual way of getting an instance of a dynamic class is to call newInstance() on the Class object.

  • What type of object is of class "NumericText" ?

    In this thread I asked the Q above.
    I can't find any object that I can drop that is of that class. And since I can't create control from the ref, I am left wondering what a "NumericText" object on the FP would be.
    Just curious,
    Ben
    Message Edited by Ben on 03-24-2009 08:47 AM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Solved!
    Go to Solution.

    The class is applicable to a numeric's "NumericText" property. Not sure about its history or purpose.
    Attachments:
    Example_VI.png ‏3 KB

  • Compiling error......class or interface expected

    here is what it said in my command prompt
    C:\j2sdk1.4.2_05\bin>javac C:\Java\Converter.java
    C:\Java\Converter.java:16: 'class' or 'interface' expected
    ^
    1 error
    and by the way sorry if this posted twice my computer is being a little annoying tonight

    here ill put the whole thing of code......dont laugh if its crappy i just started learnign this shit
    //this program requests an amount of money and gives the number of quarters, nickels, dimes, and pennies there are. The amount of money must not be less than zero.
    public class Converter
         public static void main(String[]args)
              String input;
              input = JOptionPane.showInputDialog("Enter Dollar Amount");
         public static void main(String[]args)
              String output;
              output = JOptionPane.showMessageDialog(null, "messageString", "Converter", JOptionPane.amountOfQuarters);
    public class Dollars
         String dollars; // dollar amount
         int quarters; // quarter amount
         int dimes; // dime amount
         int nickels; // nickel amount
         int pennies; // penny amount
         public Dollars(String d, int q, int d, int n, int p)
              quarters = q;
              dimes = d;
              nickels = n;
              pennies = p;
              dollars = d;
    and this is just the start i guess you could say.....i gotta make this do some equations and other crap

  • HT4623 I have wifi connection on my ipod and it tells me there is a software update as there is a no. 1 at the side of it but when i try to update if tells me unable to check for update An error has occurred while checking for a software update. why? help

    My ipod will not let me access any apps using wifi, it indicates at the top of the screen that there is a strong wifi source but it refused to work on wifi apps. I think this is because if need an update but will not let me as it says an error occurred while looking for a software update. can anyone help please thankyou. my ipod is 4th generation btw

    my ipod is not the newest update possible as i said i tried to update but it wouldnt let me as it wont let me on wifi sources such as safari facebook and other apps which use wifi.all the apps are fully updated

  • Do java programms after giving compilation error generates .class file?

    Do java programms after giving compilation error generates the .class file?
    Do any outer class may have the private as access modifier?
    If someone asks you that -do any program in java after giving a compilation error gives the .class file -do any class except(inner class)
    be defined as private or static or protected or abc or xxx Now type the
    following program
    private class test
    public static void main(String s[])
    System.out.println("Hello!How are You!!");
    -Compile it.... You must have
    received this error test.java:1:The type type can't be private. Package members are always accessible within the current package. private class
    test ^ 1 error
    Here please notify that compiler has given the
    error not the warning therfore .class file should not be created but now type
    >dir *.class
    ___________ and you will see that the
    test.class file existing in the directory nevertheless this .class file
    is executable. if you will type __________________ >java test
    it will
    wish you Hello! and suerly asks you that How are You!! ________________!
    You can test it with the following as acces modifiers and the progrm will run Ofcourse it will give you compilation error.
    protected
    xxx
    abc
    xyz
    private
    Do you have any justification?

    Hmm,
    I've been working with different versions of jdk since, if I'm not mistaken, jdk1.0.6 and never was able to get *.class with compilation errors. It was true for Windows*, Linux, and Solaris*.
    About the 'private'/'protected' modifier for the type (class) - it makes perfect sence not to allow it there: why would anyone want to create a type if no one can access it? There should be a reason for restricting your types - let's say, any inner class can be private/protected.
    For ex., you shouldn't have compile problems with this:
    class Test
    public static void main(String s[])
    System.out.println("Hello!How are You!!");
    private class ToTest{}
    Sorry, but I don't really know where you can read up on that.

  • Compile errors

    Hi, I am learning Java using a few courses from text books. Everything has been going well so far. I do most of my devleopment on Linux but recently installed the JDK on my Windows partition. The course I am using from the book comes with a library that you are to use in all the programming exercises. Anyway, this is the code from the program that I am getting a compile error on.
    import ccj.*;
    public class Fastype
    {     public static void main(String[] args);
      {          String totype = ("The quick brown fox jumps over the lazy dog.");
                double wpm;
              double sec;
              System.out.print("This program tests your typing skills. When you are ready to start press 'y'(and enter) and a sentence will appear. Type it as fast as you can without error(don't forget to press the enter key when done.) Ready?");
              String z = Console.in.readChar(); // just a statement that waits until the user is ready
              Time start = new Time();
              System.out.println(totype);
              String user = Console.in.readWord();
              Time end = new Time();
              sec = (end.getSeconds()-start.getSeconds());
              wpm = 9 * 60 / sec;
              System.out.print("Time: " + sec + "\nYou can type " + wpm + " words per minute.");
              if (user.equals(totype)) System.out.print("Good.");
              else
              if( user.compareTo(totype) != 0)
              System.out.println("  But speed is irrelevant when you type with errors.");
    }When I compile I get:
    Fastype.java:6: missing method body, or declare abstract
    {       public static void main(String[] args);
                               ^All the programs I've written so far use :
    { public static void main(String[] args)So I can't really tell whats going on here. I'm sure this is probably really stupid but I'm new to this.
    Thanks.
    IRC

    All the programs I've written so far use :
    { public static void main(String[] args)
    semicolon son,semicolon in the main method..
    tips: when the compiler gives an error ,try to take a closer look and check for the syntax of the corresponding line..
    don't worry happens to newbies...

Maybe you are looking for