Instantiating anonymous Type as method argument...

hi,
trying to do this, i guess i have stumbled upon a noob's syntax error. any help please?
    private <T extends Dimension> void fillArray(T dim, ArrayList<T> arrayList) {
        for (int i=0; i<dim.getDim();i++) {
            arrayList.add(new <T>(i+1));
    }the error is spotted in the third line and the compiler says: <identifier> expected
thnx!

you cannot do this because of the way java has defined generics. you either need some factory instance which knows how to create new T instances or a class of type T from which you can reflectively call the relevant constructor.

Similar Messages

  • DefineObserver for query with anonymous type in Streaminsight 2.1 using the Rx Framework

    Hello all,
    Assuming one has the following observable:
    var source =
    myApp.DefineObservable(() => Observable.Interval(TimeSpan.FromSeconds(1)))
    .ToPointStreamable(x => PointEvent.CreateInsert(DateTimeOffset.Now, x),
    AdvanceTimeSettings.IncreasingStartTime);
    One can write the following query:
    var query = from integer in source.TumblingWindow(TimeSpan.FromSeconds(5))
    select integer.Avg(e => e);
    And bind it to the following observer:
    var sink = myApp.DefineObserver(() => Observer.Create<double>(Console.WriteLine));
    using (query.Bind(sink).Run("Query 1"))
    Console.WriteLine("Running, press Enter to stop");
    Console.ReadLine();
    And everything works fine.
    Now let's say I want to modify the query so it can return (for example) both the average and the number of elements in the tumbling window. In that case I would modify to query like this:
    var query = from integer in source.TumblingWindow(TimeSpan.FromSeconds(5))
    select new
    Average = integer.Avg(e => e),
    Count = integer.Count()
    However, the sink is expecting a "double" not an anonymous type.
    My question is, is it possible to define a sink that can accept an anonymous type, ie. is it possible to right something like this:
    var sink = myApp.DefineObserver(() => Observer.Create<????????????????>
    (x =>
    Console.WriteLine("Average: {0} Count: {1}", x.Average,
    x.Count));
    or do I need to define a "AverageAndCount" class beforehand so I do something like:
    var query = from integer in source.TumblingWindow(TimeSpan.FromSeconds(5))
    select new AverageAndCount
    Average = integer.Avg(e => e),
    Count = integer.Count()
    };var sink = myApp.DefineObserver(() => Observer.Create<AverageAndCount>
                                              (x =>
                                               Console.WriteLine("Average: {0} Count: {1}", x.Average,
                                                                 x.Count));

    No ... you don't. There are ways around it ... there's no problem that an additional layer of abstraction can't fix, right? What you need is a way to get the type of the payload in a way that the compiler can infer it.
    From an upcoming blog post in my current series, here's an extension method that would do that with my "dual-mode sinks":
    public static IRemoteStreamableBinding BindConsumer<TPayload>(
    this IQStreamable<TPayload> stream,
    Application cepApplication,
    Type consumerFactoryType,
    object configInfo,
    EventShape eventShape)
    var factory = Activator.CreateInstance(consumerFactoryType) as ISinkFactory;
    if (factory == null)
    throw new ArgumentException("Factory cannot be created or does not implement ISinkFactory");
    switch (eventShape)
    case EventShape.Interval:
    var intervalObserver = cepApplication.DefineObserver(() => factory.CreateIntervalObserverSink<TPayload>(configInfo));
    return stream.Bind(intervalObserver);
    case EventShape.Edge:
    var edgeObserver = cepApplication.DefineObserver(() => factory.CreateEdgeObserverSink<TPayload>(configInfo));
    return stream.Bind(edgeObserver);
    case EventShape.Point:
    var pointObserver = cepApplication.DefineObserver(() => factory.CreatePointObserverSink<TPayload>(configInfo));
    return stream.Bind(pointObserver);
    default:
    throw new ArgumentOutOfRangeException("eventShape");
    Within the sink itself, you'll need to use reflection to "unpack" the event. It's not quite as straighforward - or as simple - as the untyped output adapter but it does work quite well. Keep an eye on my blog ... I should get an update posted this week that
    will get you a good ways down the path. :-)
    DevBiker (aka J Sawyer)
    Microsoft MVP - Sql Server (StreamInsight)
    If I answered your question, please mark as answer.
    If my post was helpful, please mark as helpful.

  • Method argument names

    Hey, quick question, and unfortunately I think I know the answer. I'm no expert at using reflection, but from what I can tell thus far, it is possible to get the Class name, the names of the fields in the class, and the method names. I need the names of the arguments in the methods. i.e. as a simple example:    public double quotient(double dividend, double divisor) {
            return dividend/divisor;
        }I can get the method name, the return type and the types of the arguments, but I need the actual names of the arguments. In this case I would need "dividend" and "divisor". Is this possible, and if so please let me know how?
    Thanks,
    Steve

    This is not possible with 1.5. I heared some roumor that 1.6 will provide access to argument names.

  • Questions on Linq, Anonymous Type Object

    Hi everyone,
    I am studying MVC and was following an example. I am also not expert with Lambda expressions and ANonymous types, although I have read and know the basics. However I got trapped and could not continue. I need help about this code snippets below.
    Can someone please answer my question ?
    1. how the X was inferred to be an INT ?
    2. What is the return of "new {  page = x }" ?
    3. What is the return of "Url.Action("List", new {  page = x })" ?
    4. What is the return of "x => Url.Action("List", new {  page = x })" ?
    5. This call, pageUrl(i), what does it do and where is the method declared ?
    <div class="pager">   
        @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {  page = x })) 
    </div>
     public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl) 
                StringBuilder result = new StringBuilder();
                for (int i = 1; i <= pagingInfo.TotalPages; i++)
                    TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                    tag.MergeAttribute("href", pageUrl(i));
                    tag.InnerHtml = i.ToString();
                    if (i == pagingInfo.CurrentPage)
                        tag.AddCssClass("selected");
                    result.Append(tag.ToString());
                return MvcHtmlString.Create(result.ToString());
    Thank you so much.

    Hi CodeInhinyero,
    Actually this forum is to discuss the VS usage issue, if this issue is related to web development, you could ask this question in the ASP.NET forum:
    http://forums.asp.net. If then, you could get an answer more quickly and professional.
    The MVC forum:
    http://forums.asp.net/1146.aspx
    Best Regards,
    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. <br/> Click <a
    href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.

  • LINQ: Anonymous Type Q: Missing member?

    Hi,
    Dim files = IO.Directory.GetFiles("j:\", "*.*", IO.SearchOption.AllDirectories)
    Dim q = From file In files _
    Select New IO.FileInfo(file) _
    Let bla = "a"
    For Each item In q
    Stop
    Next
    Why is the loop variable "item" of type String? I expect it to be of an anonymous type with two properties, one of type FileInfo, the other one of type String (named bla)? Just
    because the first member is not explicitly named, it mustn't be dropped. I did not write "Select bla =..." but "Let bla = ..."
    If I change it to    
        Select FI = New IO.FileInfo(File)
    it works.
    Am I missing something?
    Armin

    I can agree with this but not for everything, example, I write the following in C# where Result is an anonymous type and could easily be done with a class but then again there is much more to write this and maintain for a method that is seldom used and easy
    to read for a C# or VB.NET programmer.
    public static void FindItemAndSetChecked(this CheckedListBox sender, string Text, bool Checked)
    var Result =
    from @this in sender.Items.Cast<string>().Select(
    (item, index) => new
    Item = item,
    Index = index
    where @this.Item.ToLower() == Text.ToLower()
    select @this
    ).FirstOrDefault();
    if (Result != null)
    sender.SetItemChecked(Result.Index, Checked);
    In VB.NET Option Strict On matches the C# code
    <System.Runtime.CompilerServices.Extension> _
    Public Sub FindItemAndSetChecked(ByVal sender As CheckedListBox, ByVal Text As String, ByVal Checked As Boolean)
    Dim Result =
    From this In sender.Items.Cast(Of String)() _
    .Select(
    Function(item, index)
    Return New With {Key .Item = item, Key .Index = index}
    End Function)
    Where this.Item.ToLower() = Text.ToLower()
    Select this).FirstOrDefault()
    If Result IsNot Nothing Then
    sender.SetItemChecked(Result.Index, Checked)
    End If
    End Sub
    Setting Option Infer Off means we must create a class which is easier in VB.NET then C# i.e. using statement (equivalent to import statement) and in C# should be placed in a non-static class where VB.NET does not matter so much.
    Sure the above could be a tad tighter but in this case I don't see any benefit where there would be a benefit for applying Option Infer Off for business classes.
    Note: The above was used as I used the C# extension in a reply today and was handy to move back to VB.NET
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • Question on using table types in methods

    Hi
       I have a simple question involving passing table types in method
    I want to pass an internal table by reference - to a method and within the method populate the internal table (t1) using a select * into the internal table and then sort t1 by f1 and f2. t1 is an internal table based on a ABAP dictionary table ( at1 )
    Question is : If I use a generic type TABLE declaration , it does not allow sort operation specifically by fields. If I use type at1 as in
    the METHODS M1 exporting t1 type at1statement, syntax error is - t1 is not an internal table.
    How do I achieve the above using the method implementation ?
    Sample code that I try
    CLASS C1 DEFINITION
    PUBLIC SECTION
    METHODS M1 exporting t1 type table
    ENDMETHOD
    ENDCLASS
    CLASS C1 IMPLEMENTATION
    METHOD M1
    select * from at1 into t1.
    sort t1 field f1 f2
    ENDCLASS

    You should define a TABLE TYPE based upon the data dictionary type (at1) either in the data dictionary using SE11 or in the TYPES section of the class.
    Then define the parameter of this new type.
    Cheers
    Graham Robbo

  • Trying to uderstand different types of methods.

    Well, basically, I'm trying to uderstand the different types of methods there are.
    I uderstand private static, public static, private void and public void. Public means the method can be called from another class, private means method can only be called from within its own class. Static - some value is going to be returned, Void - no values are returned.
    These are the ones I don't understand for sure;
    static {
       try { ... }
       catch(...) { ... }
    } This method tries to do something and catches exception. But, it isn't public or private and it doesn't have a name, how does it fire?
    A void someName() method with no public or private prefix. Who can fire this method?
    final void someName(), static class someName(), and protected void someName() are other methods I don't understand.
    All help appreciated.

    Static - some
    value is going to be returned, No. Static means the method is associated with the class as a whole, not with any particular instance of the class. It has nothing to do with what, if anything, it returns.
    These are the ones I don't understand for sure;
    static {
    try { ... }
    catch(...) { ... }
    This method tries to do something and
    catches exception. But, it isn't public or private
    and it doesn't have a name, how does it fire?It's not a method. It's a static initializer. It runs when the class is loaded.
    A void someName() method with no public or
    private prefix. Who can fire this method?Without public, protected, or private, it's "default access" or "package access." It's only accessible within that class or to classes in the same package.
    >
    final void someName()[/i
    ], static class
    someName(), and protected void someName()
    are other methods I don't understand.
    You should go through a tutorial or introductory text.
    See Resources for Beginners for a list.
    http://www.thejword.com/3.html#beginner_resources

  • WSIF string(xml) to (anonymous type)

    Hi All,
    I have a WSIF service that returns a string value which is an xsd schema defined xml element. Should I leave the response type as a string and transform it in my BPEL to the element? Or should I map the string to the element within the WSIF wsdl and try and return the element itself from the WSIF? Which of the two is the better more efficient design?
    Thanks in advance.
    Message was edited by:
    user639293

    Here is a bit more details on the warning I am getting. I decide to just leave it as a string and transform it within bpel. My next question is in regards to how should I send a string to an anonymous type.
    Warning(108):
    [Error ORABPEL-10041]: Trying to assign incompatible types
    [Description]: in line 108 of "C:\projects\blah5mail\trunk\jdev_blah5mail\blah5mail\bpel\blah5mail.bpel", <from> value type "{http://www.w3.org/2001/XMLSchema}string" is not compatible with <to> value type "{http://email.blah5.com/types/}validateEmailElement anonymous type".
    [Potential fix]: Please make sure that the return value of from-spec query is compatible with the to-spec query.
    Message was edited by:
    user639293

  • Read only method arguments

    Can I make method arguments read only?? I want to send an object to a method and make it read only. i dont want a method to change public varables of the mthod argument object.
    Can anyone help me on this??
    Thanks,
    Vaijayanti

    Not possible, but you can pass a copy of the object, so that even if it's changed the changes aren't reflected to the original object.

  • Getting method arguments as hasmap

    Hi,
    can I get a method arguments in hashtable ? for example
    public void methodA(integer arg1,string arg2, integer arg3)
    so,
    is there any method in java that return a hashtable contains all method arguments , while running methodA.
    hashTable would be like this :
    arg1 1
    arg2 'a'
    arg3 5

    Bender_R. wrote:
    If you really need it, you can do it using Spring AOP. See AOP
    Edited by: Bender_R. on Oct 29, 2009 11:47 AMWhich won't give parameter names. And is unnecessary anyway, since you could just use a dynamic proxy without having to have all the Spring dependencies present

  • [svn:fx-trunk] 7825: Updating sample Java formatter for Eclipse projects to stop reformatting method arguments .

    Revision: 7825
    Author:   [email protected]
    Date:     2009-06-13 14:17:47 -0700 (Sat, 13 Jun 2009)
    Log Message:
    Updating sample Java formatter for Eclipse projects to stop reformatting method arguments.
    QA: No
    Doc: No
    Modified Paths:
        flex/sdk/trunk/development/eclipse/java/formatter.xml

    If you're still using Buckminster 3.6, I strongly suggest switching to 3.7 - it has a number of bug fixes and improvements. This applies to both headless, and the IDE (assuming Eclipse 3.7 Indigo).
    Matthew

  • Cannot send complex type as method parameter

    Cannot send complex type as method parameter
    Hi!
    I'm using a kSOAP 1.2 client and i'm having trouble executing a method that takes an object
    of complex type as parameter:
    method:
    public void addSquareDetail(SquareDetail sd){/stuff}
    -SquareDetail is a java bean class that implements KvmSerializable
    - a mapping was added to classmap
    -legacy namespace is not an issue (i AM able to execute the following methods successfully
    over kSOAP):
    -getting one SquareDetail object
    -getting a vector of squareDetail objects
    Here's how i'm trying to call the 'send' method:
         ClassMap classMap = new ClassMap();
    classMap.addMapping("urn:SquareWebService/types", "SquareDetail", (new
    SquareDetail()).getClass());
    System.out.println("add one SquareDetail");
    request = new SoapObject(serviceURN, "addSquareDetail");
    sd = new SquareDetail();
    request.addProperty("SquareDetail_1", sd);
    tx = new HttpTransport(this.endPointURL, "addSquareDetail");
    tx.debug = true;
    tx.setClassMap(classMap);
    tx.call(request); //exception here
    (above:)
    private String endPointURL = "http://localhost:8080/SquareWebService/SquareWebService";
    protected static final String serviceURN = "urn:SquareWebService/wsdl";
    Error(from server, Sun ONE App Server7):
    SoapFault - faultcode: 'env:Server' faultstring: 'Internal Server Error (deserialization
    error: unexpected XML reader state. expected: END but found: START: someInt)' faultactor:
    'null' detail: null
    Here are request/response dumps:
    -request---------
    <SOAP-ENV:Envelope xmlns:n0="urn:SquareWebService/types"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <addSquareDetail xmlns="urn:SquareWebService/wsdl" id="o0" SOAP-ENC:root="1">
    <SquareDetail_1 xmlns="" xsi:type="n0:SquareDetail">
    <someFloat xsi:type="SOAP-ENC:float">1.5</someFloat>
    <someInt xsi:type="xsd:int">-1</someInt>
    <someString xsi:type="xsd:string">someString from SquareDetail</someString>
    <propertyCount xsi:type="xsd:int">4</propertyCount>
    </SquareDetail_1>
    </addSquareDetail>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    response------------
    <?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:enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="urn:SquareWebService/types"
    xmlns:ns1="http://java.sun.com/jax-rpc-ri/internal"
    env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><env:Body><env:Fault><faultcod
    e>env:Server</faultcode><faultstring>Internal Server Error (deserialization error:
    unexpected XML reader state. expected: END but found: START:
    someInt)</faultstring></env:Fault></env:Body></env:Envelope>
    So, apparently, the request message is not understood by the server. what exactly is it
    missing, and how can i add/correct that? (my guess in SquareDetail_1 xmlns="" should be
    "urn:SquareWebService/types", although it's just a guess AND i don't know how to make kSOAP
    get it in there)
    I'm not sure what kind of SOAP parser my app server utilizes, but i'm guessing it's an
    apache product (how can i tell?). I also have a WSDL file available, should anyone be
    willing to look at it, please let me know
    thanks
    -nikita

    Don't know if it will help but Can you check if the serializable object has a public empty no args constructor with an empty call to super()
    Also make sure that a type mapping registry is added with a reference to the serializable object in it.
    Please paste The WSDL as well

  • Declaring method arguments as 'final'.

    Hi all
    Is it a good practice to declare method arguments as 'final' in java. Also please let me know how the performance would be effected.
    Ex: private int xMethod(final int i){}
    Thanks in advance.

    You are likely to find performance to be comparable whether you declare your argument as final or not.
    All it means is you cannot change the reference for an object argument or the value of a primitive argument in the method for which it is an argument.
    Note that you can still change the state of an object argument declared final! Final is not the same as const, which Java does not support.

  • Closing an anonymous stream in method call

    Will an anonymous stream in a method call be closed in the same manner an anonymous stream that is created in an object instantiation will be?
    I know this will close the anonymous FileInputStream:
    DataInputStream in =
    new DataInputStream(new FileInputStream("filename.txt"));
    /* ... code ... */
    in.close();But will this?
    MyPropertiesClass myPropertiesClass = new MyPropertiesClass();
    myPropertiesClass.store(new FileOutputStream("file.txt"));MyPropertiesClass extends Properties, and uses its store().
    I know the JavaDoc for Properties says:
    "After the entries have been written, the output stream is flushed. The output stream remains open after this method returns."
    My question is will the FileOutputStream("file.txt") be closed and garbage collected eventually after this method call because I don't have a reference to it? myPropertiesClass sticks around for a long time afterwards, will the FileOutputStream as well?
    Thanks for any insight,
    KJ

    My question is will the FileOutputStream("file.txt") be closed and garbage collected eventually after this method call because I don't have a reference to it? > myPropertiesClass sticks around for a long time afterwards, will the FileOutputStream as well?Your only hope would be if FileOutputStream overrode finalize and closed the stream there -- but it doesn't (check the API -- finalize isn't overridden). I doubt if Properties retains a reference to the OutputStream you pass to store -- why would it need to? In any case, the bottom line is that output stream isn't being closed until your process exits.
    Why not bite the bullet and rewrite that line of code so that you can explicitly close the stream?
    OutputStream out = new FileOutputStream("file.txt");
    try {
        myPropertiesClass.store(out);
    } finally {
        out.close();
    }It's not one line, but who cares? You could wrap it up in a short utility method:
    static void storeProperties(Properties properties, String path) {...}

  • Some generic anonymous class overriding methods compile, while others don't

    I have the following (stripped-down) code. The abstract class SessionHandler<T> is used by other code to define and run an operation that needs a session to something. This is best done in my code with anonymous classes, because of the shear number of operations defined. In the EntityOps<T> class, these work great. But, in the last class shown here, SomeClass, the anonymous class definition fails, though the semantics are almost identical. (List<T> vs.List<AnotherClass>) What am I doing wrong here? Or is this a bug in Java?
    Thanks, Tom
    public interface IEntityOps<T> {
        T get();
        List<t> getAll();
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
        public final T perform() {
            ... calls handle(session) ...
    // These anonymous class definitions compile fine!
    public class EntityOps<T> implements IEntityOps<T> {
        public T get() {
            T ret = null;
            ret = new SessionHandler<T>() {
                T handle(Session s) throws Throwable {
                    T ret = (some T object calculation);
                    return ret;
            }.perform();
            return ret;
        public List<T> getAll() {
            T ret = null;
            return new SessionHandler<List<T>>() {
                List<T> handle(Session s) throws Throwable {
                    List<T> ret = (some List<T> calculation);
                    return ret;
            }.perform();
    // This anonymous class definition fails with the error:
    // "SomeClass.java": <anonymous someMethod> is not abstract and does not override abstract method handle()
    //     in SessionHandler at line XX, column XX
    public class SomeClass {
        public List<AnotherClass> someMethod() throws {
            List<AnotherClass> ret = null;
            ret = new SessionHandler<List<AnotherClass>>() {
                List<AnotherClass> handle(Session s) throws Throwable {
                    List<AnotherClass> ret = (some List<AnotherClass> calculation);
                    return ret;
            }.perform();
            return ret;
    }

    I added @Override above the abstract method override, and it provides this additional error:
    "HousingConfigImpl.java": method does not override a method from its superclass at line 382, column 17
    I have also reconstructed the code layout in a separate set of classes that have no dependancies, but there's no error coming from these!
    public class CustomThing {
    public interface ISomeInterface<T> {
        List<T> interfaceMethod();
    public abstract class SomeAbstractClass<T> {
        private Class _c = null;
        public SomeAbstractClass(Class c) {
            _c = c;
        protected Class getC() {
            return _c;
        public abstract T methodToOverride(Object neededObject) throws Throwable;
        public final T finalMethod() {
            try {
                return methodToOverride(new Object());
            } catch(Throwable e) {
                throw new RuntimeException(e);
    import java.util.List;
    import java.util.Collections;
    public class SomeInterfaceImpl<T> implements ISomeInterface<T> {
        public List<T> interfaceMethod() {
            return new SomeAbstractClass<List<T>>(CustomThing.class) {
                public List<T> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    import java.util.Collections;
    import java.util.List;
    public class SomeOtherClass {
        public List<CustomThing> someMethod() {
            return new SomeAbstractClass<List<CustomThing>>(CustomThing.class) {
                public List<CustomThing> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    }So, there's something about my code that causes it to be, somehow, different enough from the example provided above so that I get the error. The only differences in the override method definitions in my actual code are in the return type, but those are different in the example above as well. Here are the class declarations, anonymous abstract class creation statements, and abstract method declarations from the actual code.
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
    public class EntityOps<T> implements IEntityOps<T> {
                return new SessionHandler<List<T>>(_mgr, _c, "getAll" + _c.getName()) {
                    List<T> handle(Session s) throws Throwable {
    public class HousingConfigImpl implements IHousingConfigOperations, ISessionFactoryManager {
                ret = new SessionHandler<List<Tenant>>((ISessionFactoryManager)this, Housing.class, "getTenantsInNeighborhood") {
                    List<Housing> handle(Session s) throws Throwable {I can't for the life of me see any syntactical difference between my example and the real code. But, one works and the other doesn't.

Maybe you are looking for