GetMethod(...) and polymorphism

Hi,
When trying to get a method by specifying not the formal parameter classes, but subclasses of it, one gets NoSuchMethodException. E.g. the add(Object) method from Collection doesn't work when one specifies Color in stead of Object as argument type.
Is the only option to write code which tries all combinations of superclasses of all arguments, or are there better solutions?
BA

I had a bit of fun once writing something to mimic the compiler's method binding. The documentation explains that it isn't perfect, but if you really want to hack it, feel free. I'll make it publicly available with a request that anyone who modifies it to fix the current limitations post their fix here. package com.akshor.pjt33.utils;
import java.lang.reflect.*;
* A non-instantiable class providing static utility methods related to
* reflection.
* @specifier Peter Taylor
* @implementer Peter Taylor
public abstract class ReflectionUtils
     * This constructor cannot be called, as it prevents subclassing.
    private ReflectionUtils()
        throw new UnknownError();
     * Simulates the compile-time binding of a method-name and a list of
     * parameter types. Whereas <code>Class.getMethod(String, Class[])</code>
     * looks for methods with the exact signature, this looks through all the
     * applicable public methods of the specified class, and selects the most
     * specific.
     * <p>
     * Note that this method will currently throw an exception if there is more
     * than one maximally specific method, even if they all have the same
     * signature. This is not quite the same as the JLS 15.12.2.2. Consider the
     * case <pre>
     *     public interface A { public void method(); }
     *     public interface B { public void method(); }
     *     public abstract class C implements A, B { }
     *     getMethod(C, "method", new Class[0]);</pre>
     * @param clazz The class in which to seek the specified method.
     * @param methodName The name of the method to seek.
     * @param paramTypes The list of parameters.
     * @return The unique maximally specific method with respect to the
     *         specified class, name and parameter types.
     * @throws NoSuchMethodException if there isn't a unique maximally specific
     *                               method, or if the name is "&lt ;init&gt ;" or
     *                               "&lt ;clinit&gt ;". (Off to file bug about JDCF
     *                               handling of HTML entities in tags).
* @throws IllegalArgumentException if any argument is null.
* @throws SecurityException if access to the information is denied.
* @see Class#getMethods()
public static Method getMethod(Class clazz,
String methodName,
Class[] paramTypes)
throws NoSuchMethodException
// Check the arguments are all non-null.
if (clazz == null || methodName == null || paramTypes == null)
throw new IllegalArgumentException();
// We don't need to check for <init> and <clinit>, because they're not
// in the list of methods returned.
// Since we assume a unique maximally specific method, we don't need to
// store a Set of maximally specific methods.
Method currentBestCandidate = null;
// Iterate through the public methods of the class.
Method[] candidates = clazz.getMethods();
for (int i = 0; i < candidates.length; i++)
// We discard non-applicable methods immediately.
if (methodApplicable(candidates, methodName, paramTypes))
// If the method is applicable, there are four cases:
// 1. currentBestCandidate is null. Store candidates[i] there.
// 2. currentBestCandidate is more specific than candidates[i].
// Discard candidates[i].
// 3. candidates[i] is more specific than currentBestCandidate.
// Store it there.
// 4. Neither candidates[i] nor currentBestCandidate is more
// specific than the other. Throw an exception.
// (Note: the JLS solution would be to case-split again: if
// both are concrete, throw the exception; if one is
// concrete, select that one; if both are abstract, pick one
// arbitrarily. However, in the latter case we really want a
// new Method whose thrown checked exceptions are formed by
// intersection of the thrown checked exceptions of the two
// abstract methods - and since Method doesn't provide any
// protected or public constructors, we can't provide such a
// Method. This is why we throw an exception).
if (currentBestCandidate == null ||
methodMoreSpecific(candidates[i], currentBestCandidate))
// candidates[i] is the new current best candidate.
currentBestCandidate = candidates[i];
else if (!methodMoreSpecific(currentBestCandidate,
candidates[i]))
// Neither method is more specific than the other.
throw new NoSuchMethodException("Ambiguity");
// If we have a best candidate, that's the method to return.
if (currentBestCandidate != null)
return currentBestCandidate;
// No such method found. Pity.
throw new NoSuchMethodException("No applicable public method");
* Checks whether or not a method is applicable to a method call. This is so
* iff the name is correct, the number of parameters is correct, and each of
* the call's parameter types is assignable to the method's corresponding
* parameter type.
* @param m The method to check for applicability.
* @param name The required method name.
* @param paramTypes The required parameter types.
* @return Whether or not the method is applicable to the name and parameter
* types.
* @throws IllegalArgumentException if any parameter is null.
private static boolean methodApplicable(Method m,
String name,
Class[] paramTypes)
// Check the parameters are non-null.
if (m == null || name == null || paramTypes == null)
throw new IllegalArgumentException();
// Check that the name corresponds.
if (!m.getName().equals(name))
return false;
// Get the parameter types of the method, and check that the number of
// parameters corresponds.
Class[] actualParamTypes = m.getParameterTypes();
if (actualParamTypes.length != paramTypes.length)
return false;
// Check that all of the parameter types are assignable.
for (int i = 0; i < paramTypes.length; i++)
if (!actualParamTypes[i].isAssignableFrom(paramTypes[i]))
return false;
// All tests pass.
return true;
* Checks whether or not the first parameter is more specific than the
* second parameter. This is the case iff the declaring class of
* <code>more</code> is assignable to the declaring class of
*<code>less</code> and each of the parameters of <code>more</code> is
* assignable to the corresponding parameter of <code>less</code>. (The
* observant will notice that the test is a &ge; rather than a > test).
* @param more The method to check for being more specific.
* @param less The method to check for being less specific.
* @return Whether or not <code>more</code> is more specific than
* <code>less</code>.
* @throws IllegalArgumentException if either parameter is null, or if they
* have different names or numbers of
* parameters.
private static boolean methodMoreSpecific(Method more, Method less)
// Check that both of the parameters are non-null.
if (more == null || less == null)
throw new IllegalArgumentException("Null parameter");
// Check that they have the same names.
if (!more.getName().equals(less.getName()))
throw new IllegalArgumentException("Different names");
// Get their parameter types and check that they have the same number of
// parameters.
Class[] moreParamTypes = more.getParameterTypes();
Class[] lessParamTypes = less.getParameterTypes();
if (moreParamTypes.length != lessParamTypes.length)
throw new IllegalArgumentException("Different numbers of params");
// To be more specific, more needs to have a declaring class assignable
// to that of less.
if (!less.getDeclaringClass().isAssignableFrom(
more.getDeclaringClass()))
return false;
// To be more specific, more has to have parameters assignable to the
// corresponding parameters of less.
for (int i = 0; i < moreParamTypes.length; i++)
if (!lessParamTypes[i].isAssignableFrom(moreParamTypes[i]))
return false;
// All tests passed.
return true;

Similar Messages

  • Errors in getMethod and invoke   ??!!!!

    when i write the following code i get a compilation error :
    Field[] fields = obj.getClass().getDeclaredFields();
    Class c = obj.getClass();
    for (int i = 0; i < fields.length; i++)
    String fieldName = fields.getName();
    if(!Modifier.isFinal(fields[i].getModifiers()))
    if(fields[i].getType().isPrimitive())
    //put its value directly
    String firstChar = fieldName.substring(0,1).toUpperCase();
    String methodName = "get" + firstChar + fieldName.substring(1);
    Method m=c.getMethod(methodName);
    if (m!=null)
    Node childPrim;
    childPrim=document.createElement(fieldName);
    parent.appendChild(childPrim);
    Text newText = document.createTextNode( (String)m.invoke(obj) );
         childPrim.appendChild(newText);
    the compilation errors are at the getMethod ---> NoSuchMethodException
    and at m.invoke(obj) ----> IllegalAccessException
    anyone has any idea how to solve that??!!!

    i wrote the rest of the code the only errors appear in getMethod and invoke everything else is OK i guess i will copy and paste the code of saving object
    thanks soo much and i am soo sorry to disturb u
    public void ObjectToNode(J obj,Document document,Node parent)
              Node childNode;
              Element tagName;
              SaveXMLFile save;
              Field[] fields = obj.getClass().getDeclaredFields();
              Class c = obj.getClass();
              for (int i = 0; i < fields.length; i++)
                   String fieldName = fields.getName();
                   if(!Modifier.isFinal(fields[i].getModifiers()))
                        if(fields[i].getType().isPrimitive())
                             //put its value directly
                             String firstChar = fieldName.substring(0,1).toUpperCase();
                             String methodName = "get" + firstChar + fieldName.substring(1);
                             Method m=c.getMethod(methodName);
                             if (m!=null)
                                  Node childPrim;
                                  childPrim=document.createElement(fieldName);
                                  parent.appendChild(childPrim);
                                  Text newText = document.createTextNode( (String)m.invoke(obj) );
                                  childPrim.appendChild(newText);
                        else if(fields[i].getType().isArray())
                             //appends each element as a child and check if it is not primative datatype
                             Node childArray;
                             childArray=document.createElement(fieldName);
                             parent.appendChild(childArray);
                             save= new SaveXMLFile();
                        else
                             String firstChar = fieldName.substring(0,1).toUpperCase();
                             String methodName = "get" + firstChar + fieldName.substring(1);
                             Method m = c.getMethod(methodName);
                             if (m!=null)
                                  if(m.invoke(obj)!=null) // call the getter
                                       Node childObj;
                                       childObj=document.createElement(fieldName);
                                       parent.appendChild(childObj);
                                       save= new SaveXMLFile();
                                       save.ObjectToNode(m.invoke(obj),document,childObj);
                             else
                                  String valueStr="";
                                  valueStr=fields[i].toString();
                                  Node childObj;
                                  childObj=document.createElement(fieldName);
                                  parent.appendChild(childObj);
                                  Text newText = document.createTextNode( valueStr );
                                  childObj.appendChild(newText);

  • Diffence between OVERLOADING and POLYMORPHISM

    hi all
    i need the differneces between
    overloading and polymorphism (atleast 3 differences :)))
    regards,
    venkat.

    can u send me any list of core java questions if u have. http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Concept of Abstraction and Polymorphism

    Hi friends,
    I'm just new to Java.I studied a little bit of C, I'm currently studing VB and Java.
    There are one or two concepts in Java that are very hard to grasp for me.
    The first is abstraction and the second is polymorphism.
    Can anybody outline to me in simple words(use simple example if needed)what those 2 concepts are all about?
    Thanks a lot
    Marco

    In your example, you could make Vehicle an abstract
    class. You can't simply have a vehicle, but you can
    have a car which IS a vehicle. In your abstract class
    Vehicle, you might define an abstract method public
    int getSeats() (you want it to be abstract because it
    changes from one type of vehicle to the next). So the
    class Car extends Vehicle, overrides the method
    getSeats() and returns 5. The class Ute extends
    Vehicle, overrides the method getSeats() and returns 2
    (you might make a SuperCabUte that extends Ute and
    returns 5, or whatever).Radish is right,
    Think of it as modelling of real life. You would generalise the description of your car as a Vehicle (abstraction, which can be implemented as an interface in Java) where in fact you own a car
    Similarly you can have an inteface called RealEstate where in fact you own a TwoStoreyHouse ( a class that implements the RealEstate interface)
    the interface can describe the general 'characterstics' of real estate properties ie land size, council rates etc.
    HTH...hey....

  • Abstract Class and polymorphism - class diagram

    Hi,
    ]Im trying to draw a class diagram for my overall system but im not too sure how to deal with classes derived from abstract classes. I'll explain my problem using the classic shape inheritance senario...
    myClass has a member of type Shape, but when the program is running shape gets instantiated to a circle, square or triangle for example -
    Shape s = new circle();
    since they are shapes. But at no stage is the class Shape instantiated.
    I then call things like s.Area();
    On my class diagram should there be any lines going from myClass directly to circle or triangle, or should a line just be joining myClass to Shape class?
    BTW - is s.Area() polymorphism?
    Thanks,
    Conor.

    Sorry, my drawing did not display very well.
    If you have MyClass, and it has a class variable of type Shape, and the class is responsible for creating MyClass, use Composition on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it has a class variable of type Shape, and the class is created elsewhere, use Aggregation on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it is used in method signatures, but it is not a class variable, use Depedency on your UML diagram to link Shape and MyClass. The arrow will point to Shape.
    Shape and instances of Circle, Triangle, Square, etc. will be linked using a Generalization on your UML diagram. The arrow will always point to Shape.
    Anything that is abstract (class, method, variable, etc.) should be italicized. Concrete items (same list) should be formatted normally.
    BTW, the distinction between Composition, Aggregation and Dependency will vary from project to project or class to class. It's a gray area. Just be consistent or follow whatever guidelines have been established.
    - Saish

  • Forums - How to use java.lang.Class.getMethod() and java.lang.reflect.Metho

    I have similar question. I am trying to invoke a method with no parameters. I don't know how to do that. Can someone please help.
    for example.
    I have 2 methods.
    public void setMethod(String strPut){
    this.strPut = strPut;
    public String getMethod(){
    return strPut;
    Method method = objRef.class.getMethod("setMethod", new Class[]{String.class});
    Object objReturn = method.invoke(sqlWhere, new Object[] {"any String"});
    I can invoke setMethod but I don't know how to invoke getMethod().

    Hi
    Try using something like this...
    CustomClass objCustomClass = new CustomClass ();
    Class customClass = objCustomClass.getClass ();
    Method m = customClass.getMethod ("getMethodName", (Class[])null);
    String strContent = (String) m.invoke (objCustomClass, null);
    Thanks and regards,
    Pazhanikanthan. P

  • Help with my Project - Includes Arrays, Inheritance and Polymorphism

    COMP 1900 CS1: Introduction to Programming
    Programming Assignment 4
    Objectives:
    * To work with superclasses and subclasses
    * To work with an abstract class
    * To gain experience working with an array of objects
    Requirements:
    * Understanding of arrays (Sections 7.1-7.3)
    * Understanding of inheritance (Chapter 8)
    * Understanding of polymorphism (Sections 9.1-9.2)
    Assignment:
    Write a Java application for a company payroll that has three different types of employees: secretary, junior salesman and senior salesman.
    * Design an employee superclass that contains an instance variable for the employee name. In addition, there should be an (abstract) method to compute the yearly bonus that employees receive in the month of December.
    * Design subclasses for each type of employee. The secretary subclass should have two instance variables: one corresponding to the initial year of employment and the other representing the salary. The junior salesman class has instance variables for base salary, total sales, and commission rate. The senior salesman class has one instance variable representing the total sales.
    * Design get and set methods for each class. Each class should also have a toString method.
    * Design a computeCommission method for each of the salesman classes as follows:
    o For a junior salesman, the commission rate is set.
    o For a senior salesman, the commission rate is variable based on total sales.
    For sales < $10,000,000: the commission rate is 0.1%;
    For sales between 10 and 25 million inclusive, the commission rate is .2%;
    For sales over 25 million, the commission rate is .25%.
    * Design a computeBonus method for all employee classes as follows:
    o For secretarial staff, bonuses are dependent on the number of years that an employee has worked for the company. If an employee has worked less than 5 years, the bonus is $50; for 5 to 10 years, inclusive, the bonus is $75; for over 10 years, the bonus is $100.
    o For junior salesman, the bonus is .01% times the sum of the yearly salary and the total commission for the year.
    o For senior salesman, the bonus is .025% of the total sales.
    * Design a class EmployeePayroll that has an instance variable that is an array of Employee objects.
    * Design methods addEmployee and toString.
    * Design a method that computes the average of all employee bonuses.
    * Design the method that counts how many employees received a bonus bigger than the number sent in as parameter.
    * Design a method that finds the employee that has earned the biggest bonus.
    * Design a class TestEmployeePayroll that creates an array with 9 Employee objects (3 of each type) and tests each of the methods that you wrote. Initially, for testing purposes you can hardcode the values for Employee objects being created, but when completed you need to ask for interactive input from the user.
    I am having trouble with how to write an abstract method to compute the yearly bonus inside of the employee superclass.
    I am also having a lot of trouble with the EmployeePayroll class. I can't think of the best way to do the addEmployee method. I am just getting stuck and very frustrated. Help would be greatly appreciated. Thanks.

    This is all I have so far.
    public class Employee
        protected String name;
        public void setName(String name)
            this.name = name;
        public String getName()
            return name;
    public class Secretary extends Employee
        private int initialYear = 0000;
        private double salary = 0.0;
        public void setInitialYear(int initialYear)
            this.initialYear = initialYear;
        public int getInitialYear()
            return initialYear;
        public void setSalary(double salary)
            this.salary = salary;
        public double getSalary()
            return salary;
        public double computeBonus()
            double bonus = 0.0;
            if(2007 - initialYear < 5)
                bonus = 50.00;
            else if(2007 - initialYear >= 5 && initialYear <= 10)
                bonus = 75.00;
            else if(2007 - initialYear > 10)
                bonus = 100.00;
            return bonus;
        public String toString()
            return "Initial Year: " + initialYear + ". Salary: " + salary + ". Bonus: " + computeBonus() + ".";
    public class JuniorSalesman extends Employee
        private double baseSalary = 0.0;
        private double commissionRate = 0.0;
        private double totalSales = 0.0;
        public void setBaseSalary(double baseSalary)
            this.baseSalary = baseSalary;
        public double getBaseSalary()
            return baseSalary;
        public void setCommisionRate(double commissionRate)
            this.commissionRate = commissionRate;
        public double commissionRate()
            return commissionRate;
        public void setTotalSales(double totalSales)
            this.totalSales = totalSales;
        public double getTotalSales()
            return totalSales;
        public double computeBonus()
            return .001 * (baseSalary + commissionRate);
        public String toString()
            return "Base Salary: " + baseSalary + ". Total Sales: " + totalSales + ". Commission Rate: " + commissionRate + ". Bonus: " + computeBonus() + ".";
    public class SeniorSalesman extends Employee
        double totalSales = 0.0;
        public void setTotalSales(double totalSales)
            this.totalSales = totalSales;
        public double getTotalSales()
            return totalSales;
        public double computeCommission()
            double commissionRate = 0;
            if(totalSales < 10000000)
                commissionRate = 0.001;
            else if(totalSales >= 10000000 && totalSales <= 25000000)
                commissionRate = 0.002;
            else if(totalSales > 25000000)
                commissionRate = 0.0025;
           return commissionRate;
        public double computeBonus()
            return totalSales * .0025;
        public String toString()
            return "Total Sales: " + totalSales + ". Commission Rate: " + computeCommission() + ". Bonus: " + computeBonus() + ".";
    }

  • How to use java.lang.Class.getMethod() and java.lang.reflect.Method.invoke(

    I want to call a specified method of one class dynamically. I use the method
    "getMethod()" in package "java.lang.Class" to get method and "invoke()" in
    " java.lang.reflect.Method " to invoke method.
    The problem is as following :
    1. There are two argument in this method "getMethod(String MethodName , Class[] paremterTypes)" in package "Class". I have no idea about the second parameter " Class[] parameterTypes ".what does the argument exactly mean ?
    2. There are two argument in the method "invoke(object obj, object[] obj)" in package "Method".
    I have no idea about the second parameter "object[] obj ".what is mean ?
    I pass " null " value to it and it works.But i pass anothers ,jvm will throw exception.

    I have a generic Method Executer that has a method like
    public Object execute(String className, String methodName, Object args)
        String fullClassName = packageName + className ;
        Class delegateClass = Class.forName(fullClassName);
        BaseDelegate delegate = (BaseDelegate)delegateClass.newInstance();
        Method method = null;
        if (args == null)
            method = delegateClass.getMethod(methodName, new Class[] {});
            obj = method.invoke(delegate,new Object[] {});
        else
            method = delegateClass.getMethod(methodName, new Class[] {args.getClass()});
            obj = method.invoke(delegate, new Object[]{args});
       }This seems to have problems when I call the method from a class like:
    execute("CategoryDelegate", "getCategoryById", new Integer(4144));(I get a NoSuchMethodException)
    The method I am trying to execute in CategoryDelegate looks like:
    public Category getCategoryById(int categoryId) throws DelegateExceptionI think it has to deal with the difference in the way we handle Primitive Wrappers and Objects. Wrapper we have to use Interger.TYPE and with the rest of the Objects we have to use obj.class.
    Am I doing something wrong here? Any suggestions to make it work for primitive wrappers as well as Objects?

  • Method signature (Chapter : Abstract class and Polymorphism)

    Hi all,
    I found some quaint thing about signature method. It's said: "A child class may define additional methods with signatures different from the parent's method." but
    "It is an error if a child defines a method with the same signature as a parent method, but with a different return type."
    The thing is: return type is not belong to method's signature !!!
    Can someone explain this point?
    Thanks and have a nice day ( 11:00 am in Germany)
    H.A

    "It is an error if a child defines a method with the
    same signature as a parent method, but with a
    different return type."
    The thing is: return type is not belong to method's
    signature !!!
    Can someone explain this point?Yes.
    Even though return type isn't part of the "signature" (as the JLS defines "signature"), the JLS requires that child methods with the same signature as parent classes have the same return type.
    Think about it for a minute: Return type isn't part of the signature, but it is part of the contract. If Parent has public Whatsit foo() then it's promising that every instance of Parent, AND every instance of any Child that is a subclass of Parent (since a Child also IS A Parent), will have that method, and callers of that method will receive a Whatsit as a return value.
    If I try to override it in Child with public Doobley foo() then a call might try to do this: Parent parent = factory.createParent(); // happens to return a Child, which is allowed, because a Child is a Parent
    Whatsit w = parent.foo(); // OH NO! We got bad a Doobley instead of a Watsit! See the problem?
    Now, it turns out that 1.5 adds covariant return types, which allows a child method to return a subtype of what the parent returns. So the above would work IFF Doobley is a subclass or subinterface of Whatsis, or is a class that implements Whatsis. This works because the child is still keeping the parent's contract. He's just actually promising a bit more than what the parent promises.

  • WebService generation and polymorphic behavior

    I have a simple problem.
    Class A has an attribute of type Class B
    Class B has 2 subclasses, Class C and Class D.
    (it holds only a reference to Class B, but at runtime will be assigned
    instances of Class C and Class D).
    Lets say Stateless EJB has a method called getMyClassA() : Class A
    The servicegen tool will not generate mappings or serializers/deserializers
    for Class C and Class D because they are not referenced directly
    (statically) from within serialized chain of classes. If I make a fake
    (unused) attribute in Class A of type Class C and Class D, everything is
    created and all works fine.
    I tried to use the <autotype> and <source2wsdd> but I need to run then it
    twice. Once with the EJB interface, and once with the supporting classes
    (class C & D). Unfortunately I then have to manually merge the 2 deployment
    descriptors because the <source2wsdd> task doesn't support the
    "mergeWithExistingWs" attribute as specified in the documentation.
    Has anybody encountered this problem?
    Thanks,
    Mark

    When I upgraded to 8.1 from the beta it seemed to magically work!
    Thanks,
    Mark
    "manoj cheenath" <[email protected]> wrote in message
    news:[email protected]...
    Thanks for trying out my suggestion.
    It looks like the problem is because you are
    using 8.1beta. WLS 8.1 GA is available for
    download. Please try it out.
    I wrote an example similar to your usecase
    and it seems to work fine in WLS 8.1.
    Checkout the example attached.
    Regards,
    -manoj
    http://manojc.com
    "Mark Fine" <[email protected]> wrote in message
    news:[email protected]...
    Yes, i'm using the WLS8.1beta.
    Originally, I was using the "copied.xml" file. That does not "merge".
    It
    works as stated in the autotype documentation, it excludes the types
    specified in the "typeMapping" file so the new types.xml file onlycontains
    types that are not in the "copied.xml" file.
    The source2wsdd task is needed to merge two deployment descriptors intoone,
    but unfortunately the documented parameter "mergeExistingWS" doesn't
    work
    in
    8.1 (documented bug).
    Is there any workaround for this other than manually merging thedeployment
    descriptors.
    M
    "manoj cheenath" <[email protected]> wrote in message
    news:[email protected]...
    You are using WLS 8.1?
    Also can you please try the secound autotype with
    the copied.xml file. I suspect that the old types.xml
    file is overwritten before loading it.
    <autotype
    javaComponents="${service.class}"
    targetNamespace="${webservice.machine.url}"
    destDir="${autotype.dir}"
    typeMappingFile="${autotype.dir}/copied.xml"
    >I have not tried this type of example. So this is a
    wild guess :-)
    Regards,
    -manoj
    http://manojc.com
    "Mark Fine" <[email protected]> wrote in message
    news:[email protected]...
    I tried running autotype for both class C & D, and for the EJB. It
    simply
    overwrites the first types.xml.
    To confirm the problem I copied the result of autotype C & D to aseparate
    file and saw that its contents were not merged.
    Here are my tasks:
    <autotype
    javatypes="C, D"
    targetNamespace="${webservice.machine.url}"
    destDir="${autotype.dir}">
    <classpath>
    <path refid="webservice-build-classpath" />
    <pathelement location="${autotype.dir}" />
    </classpath>
    </autotype>
    <copy tofile="${autotype.dir}/copied.xml"
    file="${autotype.dir}/types.xml"/>
    <autotype
    javaComponents="${service.class}"
    targetNamespace="${webservice.machine.url}"
    destDir="${autotype.dir}"
    typeMappingFile="${autotype.dir}/types.xml"
    >
    <classpath>
    <path refid="webservice-build-classpath" />
    <pathelement location="${autotype.dir}" />
    </classpath>
    </autotype>
    "manoj cheenath" <[email protected]> wrote in message
    news:[email protected]...
    In 8.1 you can run autotype on class C and D to generate
    the types.xml file. Then run autotype on the ejb interface
    by passing in the types.xml file generated before. The
    secound autotype should merge the type.xml files. I have
    not tried this out, but a similar example is here.
    http://www.manojc.com/?sample8
    Regards,
    -manoj
    http://manojc.com
    "Mark Fine" <[email protected]> wrote in message
    news:[email protected]...
    I have a simple problem.
    Class A has an attribute of type Class B
    Class B has 2 subclasses, Class C and Class D.
    (it holds only a reference to Class B, but at runtime will be
    assigned
    instances of Class C and Class D).
    Lets say Stateless EJB has a method called getMyClassA() : Class
    A
    >>>>>>
    The servicegen tool will not generate mappings orserializers/deserializers
    for Class C and Class D because they are not referenced directly
    (statically) from within serialized chain of classes. If I make
    a
    fake
    (unused) attribute in Class A of type Class C and Class D,
    everything
    is
    created and all works fine.
    I tried to use the <autotype> and <source2wsdd> but I need to
    run
    then
    it
    twice. Once with the EJB interface, and once with the
    supporting
    classes
    (class C & D). Unfortunately I then have to manually merge the
    2
    deployment
    descriptors because the <source2wsdd> task doesn't support the
    "mergeWithExistingWs" attribute as specified in the
    documentation.
    >>>>>>
    Has anybody encountered this problem?
    Thanks,
    Mark

  • WScompile and polymorphism

    Hi,
    I have some probleme to generate a wsdl file with wscompile tool.
    I have a class A with a1 as attribute.
    a class B who extends A, with b1 as attribute
    In my interface class, I have a method : getB who's return a B class.
    When I generate my WSDL file from this interface, the type B is defined with a1 and b1 as attribute. I would like to have an objet A with attribute a1 and a class B with attribute b1 with an extension base of type A
    thanks for your help

    Try adding an <additionalTypes> element to your configfile that you pass to wscompile and add class A.
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration
         xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
    <service name="HelloFaultCombined_Service"
    targetNamespace="http://echoservice.org/wsdl"
    typeNamespace="http://echoservice.org/types"
    packageName="stub_tie_generator_test">
         <interface name="stub_tie_generator_test.Hello"
         servantName="stub_tie_generator_test.HelloImpl"
                        soapActionBase="http://stub_tie_generator_test.Hello/"/>
         <interface name="stub_tie_generator_test.Fault"
         servantName="stub_tie_generator_test.FaultImpl"
                        soapActionBase="http://stub_tie_generator_test.Fault/"/>
         <typeMappingRegistry>
    <additionalTypes>
    <class name="stub_tie_generator_test.MultiArgFault"/>
         </additionalTypes>
         </typeMappingRegistry>
    </service>
    </configuration>

  • Super and Polymorphism

    I have a class called Player and a subclass that extends
    player called CompPlayer. Here is my code for the player class
    (only that which relates to this topic):
    class Player
    //Class properties
    //Private Members
    private var m_PicFile:String;
    //Class Methods
    public function Player(picFile:String)
    this.m_PicFile = picFile;
    public function getPicName():String
    trace("HERE I AM");
    return this.m_PicFile;
    The CompPlayer class looks like:
    class CompPlayer extends Player
    //Class properties
    //Private Members
    private var m_PlayStyle:Number;
    //Class Methods
    public function CompPlayer(picFile:String, playStyle:Number)
    super(picFile, name, age, gender);
    this.m_PlayStyle = playStyle;
    public function getPicName()
    super.getPicName();
    I then instantiate a CompPlayer:
    var comp:CompPlayer = new CompPlayer("picture.png", 2);
    I then run the following code:
    comp.getPicName();
    In the debug screen, I get "HERE I AM" and "undefined". This
    is the problem. It calls the correct method, but cannot access the
    variable. If I delete the getPicName() inside of the CompPlayer
    class, it works just fine and outputs "HERE I AM" and
    "picture.png". Anybody know what is going on here? Why can't I
    access the m_PicFileName using the super.getPicName() from the
    CompPlayer class?

    Don't know where the undefined comes from -- you must have
    omitted some
    code. I made a couple minor changes (see below) and it works
    for me.
    <SNIP>
    > //Class Methods
    > public function CompPlayer(picFile:String,
    playStyle:Number)
    > {
    > super(picFile, name, age, gender); // error here -- will
    not
    compile
    super(picFile)
    > this.m_PlayStyle = playStyle;
    > }
    >
    > public function getPicName()
    > {
    > super.getPicName();
    return super.getPicName();
    > }
    >
    >
    > }
    >
    >
    > I then instantiate a CompPlayer:
    > var comp:CompPlayer = new CompPlayer("picture.png", 2);
    >
    > I then run the following code:
    > comp.getPicName();
    trace(comp.getPicName());
    OUTPUT:
    HERE I AM
    picture.png

  • EJB and polymorphism

    Is it allowed to use polymorphism on the remote interface of an EJB?
    I think the following is correct, however my IDE does not accept it.
    public RegadrVO getRegadr(int regadrNr) throws RemoteException;
    public int getRegadr(RegadrExistsVO regadrExistsVO) throws RemoteException;
    Thank you.

    You cannot change the return type of the methods. That violates the rule of polymorphism. Though the parameters can be different.

  • Can polymorphism be implemented with the GOOP toolkit? And has anyone experimented with ObjectVIEW? How does it compare to the GOOP toolkit?

    I have not experimented with the GOOP toolkit yet, but have done a little with ObjectVIEW.

    Hi,
    Inheritance and polymorphism (implemented as dynamic binding by virtual methods)are supported in the GOOP Inheritance Toolkit from Endevo.
    Please check the following link:
    http://www.endevo.se/default.asp?lang=eng (click on products).
    Regards,
    Mattias Ericsson
    Endevo
    Main developer of the GOOP Inheritance Toolkit

  • Error with instance variable and constructor of base class

    I am getting the error on the following statement "protected Point apoint" of by base class. What is causing this problem? See my code:
    package Shapes;
    public abstract class Shapes
         protected Point apoint; / ****error at this line****/
         public void move(double xdelta, double ydelta)
              apoint.x += xdelta;
              apoint.y += ydelta;
    public abstract void distance();
    public abstract void show();
    public String toString()
    return "\nThe starting point is at coordinates ("+x+","+y+")";
    package Shapes;
    public class Lines extends Shapes
    protected Point start;
    protected Point end;
         protected double x;
         protected double y;
         double delta;
         public Lines( final Point apoint, final Point bpoint)
    start.x = apoint.x;
              start.y = apoint.y;
              end.x = bpoint.x;
              end.y = bpoint.y;
    public Lines(double xstart, double ystart, double xend, double yend)
    this.xstart = xstart;
              this.ystart = ystart;
              this.xend = xend;
              this.yend = yend;
         public Lines(double x, double y)
              this.x = x;
              this.y = y;
                   public void distance(final Lines start, final Lines end)
                        delta = abs(Math.sqrt (super.x - start.x) * (super.x - end.x) +
                        (super.y - start.y) * (super.y - end.y));
                   Lines move(Point start, double delta)
                        end.x += delta;
                        end.y += delta;
                        return new Point(end);
    public Lines show()
    g.drawLine( start.x, start.y, end.x, end.y);
    public String toString()
    return super.toString()+ "\n moved distance is("
                   + start + ") : (" + end + ")"
                   +" \n to position(" + start + " ) : (" + end + ")";
    package Shapes;
    public class Rectangle extends Lines
         double delta;
    public Rectangle (Point top_lft_pt, Point bottom_rght_pt)
    super(top_lft_pt, bottom_rght_pt);
    public Rectangle(double x_top_lft, double y_top_lft, double x_bottom_rght, double y_bottom_rght)
    super(x_top_lft, y_top_lft, x_bottom_rght, y_bottom_rght);
         public Rectantgle is_it_diagonal()
              if(top_lft.x > bottom_rght.x && bottom_rght.x < top_lft.x)
                   System.out.println("Point are Not Diagonal");
                   public void distance(double delta)
                        delta = abs(Math.sqrt (top_lft.x - bottom_rght.x) * (top_lft.x - botton_rght.x) +
                        (top_lft.y - bottom_rght.y) * (top_lft.y - bottom_rght.y));
                   public Rectangle move(final Point top_lft_pt, double delta)
                        bottom_rght.x += delta;
                        bottom_rght.y += delta;
                        return new Point(bottom_rght_pt);
                   public void get_top_rght_coords()
                        Point top_rght = new Point();
                        top_rght.x = bottom_rght.x;
                        top_rght.y = top_lft.y;
                   public void get_bottom_left_coords()
                        Point bottom_lft = new Point();
                        bottom_lft.x = top_lft.x;
                        bottom_lft.y = bottom_rght.y;
         public Rectangle show()
                        g.drawLine(top_lft.x, top_lft.y, top_rght_x, top_rght_y);
                        g.drawLine(bottom_lft.x, bottom_lft.y, bottom_rght.x, bottom_rght.y);
                        g.drawLine(top_lft.x, top_lft.y, bottom_lft.x, bottom_lft.y);
                        g.drawLine(top_rght.x, top_rght.y, bottom_rght.x, bottom_rght.y);
    package Shapes;
    public class Circles extends Lines
    protected double radius;
         public double delta;
         protected Point center;
    public Circles(double x, double y, double radians)
    super(x, y);
              radius = radians;
         public Circles(Point acenter)
              center.x = acenter.x;
              center.y = acenter.y;
    public void distance()
    delta = abs(Math.sqrt(super.x - x) * (super.x - x) + (super.y - y) * (super.y -y));
         public Circles move(final Point Circles, double delta)
              return new Point(Circles);
    public void show()
    g.drawOval(Circles.x, Circles.y, radius, radius);
    package Shapes;
    import java .math .*;
    import java.util .Random ;
    public class ShapesDriver
    Shapes[] aShape = new Shapes[10];
    static double range = 101.0;
    static Random r1 = new Random();
    public static void main(String [] args)
    double[][] coords = new double[10][10];
    double[] radians = new double [10];
    Shapes anyShape = {
    new Circles(radians),
    new Lines(coords),
    new Rectangle(coords)
    Shapes aShape; /***error at this line***/
              for(int i = 1; i <= coords.length; i++)
    for(int j = 1; j <= coords.length; j++)
                                                      coords[i][j] = r1.nextDouble () * range;
                                                      radians[j] = r1.nextDouble () * range;
    aShape[i] = anyShape[r1.nextInt(aShape.length)];
    System.exit(1);

    Thanks for your help with this problem. Now I have another problem that I am having a hard time figuring out. My program is using inheritance and polymorphism. I trying to use only one version of methods in the superclass points which extends the shapes class which is the abstract superclass vs. repeating the implementation of the methods (move, show, etc.) in each of the subclasses. The error I am getting is this "declare the class abstract, or implement abstract member 'Point Shapes.move()'. As you see, move is declared abstract and of type point in the Shapes superclass and it's behavior is implemented in the subclass Points extending Shapes. The other subclasses, circle, rectangle and lines will invoke the move method from Points and return a new point object. Why I am I getting the error to declare or implement move when the implementation is in Point?
    Below is code, please help?
    import java .awt .Point ;
    public class ShapesDriver
         public static void main(String args[])
              int count = 0;
              int choice;
              Point start = null;
              Point end = null;
              System.out .println(" 1 i am here");
              start = new Point((int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
              end = new Point((int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
         System.out .println(" 2 i am here");     
         System.out.println (start);
         System.out.println(end);                         
         for(int i = 0; i <= count; i++)
              System.out .println(" 3 i am here");
              choice = (int)(4.0 * Math.random());
              System.out .println(" 4 i am here");
              System.out.println (choice);     
         switch(choice)
              case 0: //Lines
              System.out .println(" 5 i am here");
              Lines apoint = new Lines((int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                                  (int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
              Point coords = new Point((int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
              new Point((int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
              break;
              case 1: //Circles
              System.out .println(" 6 i am here");
              Circles center = new Circles((double)(Math.random()* 10.0),
              (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
              (double)(Math.random()* 10.0),(double)(Math.random()* 10.0));
              Circles centerpt = new Circles((int)(Math.random()* 10.0),
              (int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
              (int)(Math.random()* 10.0), (double)(Math.random()* 10.0));
         break;
              case 2: //Rectangles
         System.out .println(" 7 i am here");
              Rectangle top_lft_pt = new Rectangle ((double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0));
              Rectangle bottom_rgt_pt = new Rectangle ((double)(Math.random()* 10.0),
                   (double)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
         break;
         default:
         System.out .println(" 9 i am here");
         System.out.println("\nInvalid shape choice =" + choice);
         System.exit(0);
         break;
         try
                   System.in.read();
                   catch(java.io.IOException ioe)
    import java .awt .Point ;
    public abstract class Shapes
         private String shape;
         public Shapes(String ashape)
              shape = new String(ashape);
         public abstract Point move();
         public double distance()
              return 0.0;
         public abstract void show();
         public String toString()
              return "\nThis shape is a" + shape;
    import java .awt .Point ;
    public class Rectangle extends Points
         protected Point top_lft;
         protected Point top_rgt;
         protected Point bottom_lft;
         protected double top_lft_x;
         protected double top_lft_y;
         protected double bottom_rgt_x;
         protected double bottom_rgt_y;
         protected Point bottom_rgt;
         protected double delta = 0;
         protected String shape = "Rectangle";
         public Rectangle(double x, double y, double top_lft_x,
                             double top_lft_y, double bottom_rgt_x,
                             double bottom_rgt_y)
              super(x, y);
              top_lft_x = top_lft_x;
              top_lft_y = top_lft_y;
              bottom_rgt_x = bottom_rgt_x;
              bottom_rgt_y = bottom_rgt_y;
         public Rectangle( double x, double y, Point bottom_rgt, Point top_lft)
              super(x, y);
              bottom_rgt_x = bottom_rgt.x;
              bottom_rgt_y = bottom_rgt.y;
              top_lft_x = top_lft.x;
              top_lft_y = top_lft.y;
         public String toString()
              return super.toString() + " coordinates top left= " + top_lft_x + "," + top_lft_y + "and bottom right" +
                   bottom_rgt_x + "," + bottom_rgt_y + ")";
         public void is_it_diagonal()
              if(top_lft_x < bottom_rgt_x && bottom_rgt_x > top_lft_x)
                   System.out.println("Points are Not Diagonal");
              public double distance()
                   distance ();
                   return delta;
              public Point move(Point top_lft)
                   move();
                   bottom_rgt_x += delta;
                   bottom_rgt_y += delta;
                   return top_lft;
              public void get_other_coords()
                   top_rgt.x = bottom_rgt.x;
              top_rgt.y = top_lft.y;
                   bottom_lft.x = top_lft.x;
                   bottom_lft.y = bottom_rgt.y;
              public void show()
                   super.show();
                   System.out.println("new coords are :");
                   System.out .println ("(" + top_lft_x + "," + top_lft_y + ")");
                   System.out .println ("top right(" + top_rgt + ")");
                   System.out .println ("(" + bottom_rgt_x + "," + bottom_rgt_y + ")");
                   System.out .println ("bottom right(" + bottom_rgt + ")");
    import java .awt .Point ;
    public class Points extends Shapes
         protected double delta = 0.0;
         protected double x;
         protected double y;
         protected String ashape = "Points";
         public Points( double x, double y)
              super("Points");
              x = x;
              y = y;
         public Points( Point start)
              super("Points");
              x = start.x;
              y = start.y;          
         public String toString()
              return super.toString() + "References coordinates(" + x + y + ")";
         public double distance(double x1, double y1 )
              return delta =(Math.sqrt(x - x1) * (x - x1) + (y - y1) *
              (y - y1));
         public Point move(Point pts)
              pts.x += delta;
              pts.y += delta;
              return pts;
         public void show()
              System.out.println("This shape is a" + ashape + "(" +
                                  "(" + x+ "," + y + ")");
    import java .awt .Point ;
    public class Lines extends Points
         double delta = 0;
         protected double x;
         protected double y;
         protected String ashape = "Lines";
         public Lines( double x1, double y1, double x, double y)
              super(x1,y1);
              x = x;
              y = y;
         public Lines(Point start, Point end)
              super(start);
              x = end.x;
              y = end.y;
         public String toString(Point end)
              return super.toString() + "line points = (" + x + "," + y +
                   "(" + end + ")";
         public double distance()
              distance ();
              return delta;
         public Point move(Point lines)
              move ();
              return lines;
         public void show()
              System.out.println("This shape is a" + ashape + "(" +
                                  "(" + x + "," + y + ")");
    import java .awt .Point ;
    public class Circles extends Points
    protected double radius;
    protected double xcenter;
    protected double ycenter;
    protected String ashape = "Circle";
         public Circles( double x, double y, double cx, double cy, double radians)
              super(x, y);
              xcenter = cx;
              ycenter = cy;
              radius = radians;
         public Circles( Point acenter, Point ref, double radians)
              super(ref);
              xcenter = acenter.x;
              ycenter = acenter.y;
              radius = radians;
         public String toString(Point ref)
              return super.toString() + " reference points (" +
                   ref + ")" +
                   "center coordinates (" + xcenter + "," + ycenter + ")";
              public double distance(Point ref)
                   return (Math.sqrt(ref.x - xcenter) * (ref.x - xcenter)
                             + (ref.y - ycenter) *
              (ref.y - ycenter));
              public Point move(Point center)
                   move();
                   return center;
              public void show()
                   System.out.println("This shape is a" + ashape + "(" +
                                  "(" + xcenter + "," + ycenter + ")");

Maybe you are looking for