Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Following are the two approaches: constructor with all the class properties Pros: I have to put an exact number of types of parameters so if I make an error the compiler warns me (by the way, is there a way to prevent the problem of having erroneously switched two Integer on the parameter list?) Cons: if I have lots of properties the instantiation line can become really long and it could ...
In the book "Thinking in Java" there is an example of how to get information for a bean via Reflection/Introspection. BeanInfo bi = Introspector.getBeanInfo(Car.class, Object.class); for (PropertyDescriptor d: bi.getPropertyDescriptors()) { Class<?> p = d.getPropertyType(); if (p == null) continue; [...] } In line 4 of that sample above there is a check if the PropertyType is nul...
A former colleague of mine started a discussion half an hour ago about javabeans, and why they didn't quite work the way he wants in JSF. The particular case is about boolean properties. 1. For a boolean property named isUrl Eclipse generates this private boolean isUrl; public boolean isUrl() {..} public boolean setUrl(boolean url) {..} But this does not work in JSF. He made it work by add...
can I define setter method to return this rather than void? Like: ClassA setItem1() { return this; } ClassA setItem2() { return this; } then I can use new ClassA().setItem1().setItem2()
I thought this should be obvious but I can't find it. Now that fields can have annotations, I thought this should be reflected in the JavaBean spec, but I can't find it. What I mean: JavaBean is a specification that allows you to treat objects in an uniform way by discovering their properties, and then reading and writing them. As POJOs properties can now be annotated (as in Hibernate anno...
Suppose I have a handle on an object of type , and I'm told by configuration that it has a bean property of type int with the name age. How can I retrieve the getter for this document? Is there a better way than prepending "get" and capitalizing the "a" in age, and looking for a method of that name via reflection?
I have a simple Java POJO that I would copy properties to another instance of same POJO class. I know I can do that with BeanUtils.copyProperties() but I would like to avoid use of a third-party library. So, how to do that simply, the proper and safer way ? By the way, I'm using Java 6.
What is the difference between adding a listener and setting a listener. e.g. addTextChangedListener(textWatcher); setOnClickListener(clickListener); Answer: After aioobe's answer i have tested this in my project. So we can do this. editText.addTextChangedListener(textWatcher1); editText.addTextChangedListener(textWatcher2); but we can't do this.(It will set only the last listener in t...
Java has the concept of a "bean", which is a class with a no-arg constructor and getter/setter methods. Does this pattern have a more generic name so that, if we're talking to programmers who have never used Java, we can avoid using the term "bean"?
I want to create a custom tag library but in the handler class I would like to have integer attributes. In the tld file I have the following code: <tag> <name>circle</name> <tag-class>draw.Circle</tag-class> <body-content>jsp</body-content> <attribute> <name>x</name> <require...
I am just create a One generic method using Method Reflection API. In This Method I am trying to get a particulate method(getter method / setter method) value but I am stuck I don't know how to do this. I am Abel to get all the method Name using Method Reflection API but not Abel to get value of that method. So please help me. here is my code...... /* propertyNames List is contain...
I'm trying to port some java to jruby, and it uses a beans PropertyDescriptor. The original code is: new PropertyDescriptor("splitEvaluator", CrossValidationResultProducer.class) which I've tried to port to: PropertyDescriptor.new("splitEvaluator", CrossValidationResultProducer) However, I get the error: no constructor with arguments matching [class org.jruby.RubyString, class org.jruby....
I have a datatable which provides objects from a list. Within this data table I would like to use a tag like p:columns(primefaces) which provides strings from a list that represent the name of a field. I will now need a subexpression to be able to use the dynamic field name like: #{entry.#[column.fieldName}} Is there any possibility to do this in JSF2?
In an interview my friend was asked to design a validation framework, can any one give me idea how to design a efficient framework Our approach was an interface having all method and class implementaion of all methods
  /*
   * Copyright 1996-2004 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.beans;
 
 
A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods.
 
 public class PropertyDescriptor extends FeatureDescriptor {
 
     private Reference<ClasspropertyTypeRef;
     private Reference<MethodreadMethodRef;
     private Reference<MethodwriteMethodRef;
 
     private boolean bound;
     private boolean constrained;
 
     // The base name of the method name which will be prefixed with the
     // read and write method. If name == "foo" then the baseName is "Foo"
     private String baseName;
 
     private String writeMethodName;
     private String readMethodName;

    
Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods. Thus if the argument name is "fred", it will assume that the writer method is "setFred" and the reader method is "getFred" (or "isFred" for a boolean property). Note that the property name should start with a lower case character, which will be capitalized in the method names.

Parameters:
propertyName The programmatic name of the property.
beanClass The Class object for the target bean. For example sun.beans.OurButton.class.
Throws:
IntrospectionException if an exception occurs during introspection.
 
     public PropertyDescriptor(String propertyNameClass<?> beanClass)
                 throws IntrospectionException {
         this(propertyNamebeanClass,
              . + NameGenerator.capitalize(propertyName),
              . + NameGenerator.capitalize(propertyName));
     }

    
This constructor takes the name of a simple property, and method names for reading and writing the property.

Parameters:
propertyName The programmatic name of the property.
beanClass The Class object for the target bean. For example sun.beans.OurButton.class.
readMethodName The name of the method used for reading the property value. May be null if the property is write-only.
writeMethodName The name of the method used for writing the property value. May be null if the property is read-only.
Throws:
IntrospectionException if an exception occurs during introspection.
 
     public PropertyDescriptor(String propertyNameClass<?> beanClass,
                 String readMethodNameString writeMethodName)
                 throws IntrospectionException {
         if (beanClass == null) {
             throw new IntrospectionException("Target Bean class is null");
         }
         if (propertyName == null || propertyName.length() == 0) {
             throw new IntrospectionException("bad property name");
         }
         if ("".equals(readMethodName) || "".equals(writeMethodName)) {
            throw new IntrospectionException("read or write method name should not be the empty string");
        }
        setName(propertyName);
        setClass0(beanClass);
        this. = readMethodName;
        if (readMethodName != null && getReadMethod() == null) {
            throw new IntrospectionException("Method not found: " + readMethodName);
        }
        this. = writeMethodName;
        if (writeMethodName != null && getWriteMethod() == null) {
            throw new IntrospectionException("Method not found: " + writeMethodName);
        }
        // If this class or one of its base classes allow PropertyChangeListener,
        // then we assume that any properties we discover are "bound".
        // See Introspector.getTargetPropertyInfo() method.
        String name = "addPropertyChangeListener";
        Class[] args = {PropertyChangeListener.class};
        this. = (null != Introspector.findMethod(beanClassnameargs.lengthargs));
    }

    
This constructor takes the name of a simple property, and Method objects for reading and writing the property.

Parameters:
propertyName The programmatic name of the property.
readMethod The method used for reading the property value. May be null if the property is write-only.
writeMethod The method used for writing the property value. May be null if the property is read-only.
Throws:
IntrospectionException if an exception occurs during introspection.
    public PropertyDescriptor(String propertyNameMethod readMethodMethod writeMethod)
                throws IntrospectionException {
        if (propertyName == null || propertyName.length() == 0) {
            throw new IntrospectionException("bad property name");
        }
        setName(propertyName);
        setReadMethod(readMethod);
        setWriteMethod(writeMethod);
    }

    
Creates PropertyDescriptor for the specified bean with the specified name and methods to read/write the property value.

Parameters:
bean the type of the target bean
base the base name of the property (the rest of the method name)
read the method used for reading the property value
write the method used for writing the property value
Throws:
IntrospectionException if an exception occurs during introspection
Since:
1.7
    PropertyDescriptor(Class<?> beanString baseMethod readMethod writethrows IntrospectionException {
        if (bean == null) {
            throw new IntrospectionException("Target Bean class is null");
        }
        setClass0(bean);
        setName(Introspector.decapitalize(base));
        setReadMethod(read);
        setWriteMethod(write);
        this. = base;
    }

    
Gets the Class object for the property.

Returns:
The Java type info for the property. Note that the "Class" object may describe a built-in Java type such as "int". The result may be "null" if this is an indexed property that does not support non-indexed access.

This is the type that will be returned by the ReadMethod.

    public synchronized Class<?> getPropertyType() {
        Class type = getPropertyType0();
        if (type  == null) {
            try {
                type = findPropertyType(getReadMethod(), getWriteMethod());
                setPropertyType(type);
            } catch (IntrospectionException ex) {
                // Fall
            }
        }
        return type;
    }
    private void setPropertyType(Class type) {
        this. = getWeakReference(type);
    }
    private Class getPropertyType0() {
        return (this. != null)
                ? this..get()
                : null;
    }

    
Gets the method that should be used to read the property value.

Returns:
The method that should be used to read the property value. May return null if the property can't be read.
    public synchronized Method getReadMethod() {
        Method readMethod = getReadMethod0();
        if (readMethod == null) {
            Class cls = getClass0();
            if (cls == null || ( == null &&  == null)) {
                // The read method was explicitly set to null.
                return null;
            }
            if ( == null) {
                Class type = getPropertyType0();
                if (type == boolean.class || type == null) {
                     = . + getBaseName();
                } else {
                     = . + getBaseName();
                }
            }
            // Since there can be multiple write methods but only one getter
            // method, find the getter method first so that you know what the
            // property type is.  For booleans, there can be "is" and "get"
            // methods.  If an "is" method exists, this is the official
            // reader method so look for this one first.
            readMethod = Introspector.findMethod(cls, 0);
            if (readMethod == null) {
                 = . + getBaseName();
                readMethod = Introspector.findMethod(cls, 0);
            }
            try {
                setReadMethod(readMethod);
            } catch (IntrospectionException ex) {
                // fall
            }
        }
        return readMethod;
    }

    
Sets the method that should be used to read the property value.

Parameters:
readMethod The new read method.
    public synchronized void setReadMethod(Method readMethod)
                                throws IntrospectionException {
        if (readMethod == null) {
             = null;
             = null;
            return;
        }
        // The property type is determined by the read method.
        setPropertyType(findPropertyType(readMethodgetWriteMethod0()));
        setClass0(readMethod.getDeclaringClass());
         = readMethod.getName();
        this. = getSoftReference(readMethod);
    }

    
Gets the method that should be used to write the property value.

Returns:
The method that should be used to write the property value. May return null if the property can't be written.
    public synchronized Method getWriteMethod() {
        Method writeMethod = getWriteMethod0();
        if (writeMethod == null) {
            Class cls = getClass0();
            if (cls == null || ( == null &&  == null)) {
                // The write method was explicitly set to null.
                return null;
            }
            // We need the type to fetch the correct method.
            Class type = getPropertyType0();
            if (type == null) {
                try {
                    // Can't use getPropertyType since it will lead to recursive loop.
                    type = findPropertyType(getReadMethod(), null);
                    setPropertyType(type);
                } catch (IntrospectionException ex) {
                    // Without the correct property type we can't be guaranteed
                    // to find the correct method.
                    return null;
                }
            }
            if ( == null) {
                 = . + getBaseName();
            }
            writeMethod = Introspector.findMethod(cls, 1,
                          (type == null) ? null : new Class[] { type });
            try {
                setWriteMethod(writeMethod);
            } catch (IntrospectionException ex) {
                // fall through
            }
        }
        return writeMethod;
    }

    
Sets the method that should be used to write the property value.

Parameters:
writeMethod The new write method.
    public synchronized void setWriteMethod(Method writeMethod)
                                throws IntrospectionException {
        if (writeMethod == null) {
             = null;
             = null;
            return;
        }
        // Set the property type - which validates the method
        setPropertyType(findPropertyType(getReadMethod(), writeMethod));
        setClass0(writeMethod.getDeclaringClass());
         = writeMethod.getName();
        this. = getSoftReference(writeMethod);
    }
    private Method getReadMethod0() {
        return (this. != null)
                ? this..get()
                : null;
    }
    private Method getWriteMethod0() {
        return (this. != null)
                ? this..get()
                : null;
    }

    
Overridden to ensure that a super class doesn't take precedent
    void setClass0(Class clz) {
        if (getClass0() != null && clz.isAssignableFrom(getClass0())) {
            // dont replace a subclass with a superclass
            return;
        }
        super.setClass0(clz);
    }

    
Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.

Returns:
True if this is a bound property.
    public boolean isBound() {
        return ;
    }

    
Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.

Parameters:
bound True if this is a bound property.
    public void setBound(boolean bound) {
        this. = bound;
    }

    
Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.

Returns:
True if this is a constrained property.
    public boolean isConstrained() {
        return ;
    }

    
Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.

Parameters:
constrained True if this is a constrained property.
    public void setConstrained(boolean constrained) {
        this. = constrained;
    }


    
Normally PropertyEditors will be found using the PropertyEditorManager. However if for some reason you want to associate a particular PropertyEditor with a given property, then you can do it with this method.

Parameters:
propertyEditorClass The Class for the desired PropertyEditor.
    public void setPropertyEditorClass(Class<?> propertyEditorClass) {
        this. = getWeakReference((Class)propertyEditorClass);
    }

    
Gets any explicit PropertyEditor Class that has been registered for this property.

Returns:
Any explicit PropertyEditor Class that has been registered for this property. Normally this will return "null", indicating that no special editor has been registered, so the PropertyEditorManager should be used to locate a suitable PropertyEditor.
    public Class<?> getPropertyEditorClass() {
        return (this. != null)
                ? this..get()
                : null;
    }

    
Constructs an instance of a property editor using the current property editor class.

If the property editor class has a public constructor that takes an Object argument then it will be invoked using the bean parameter as the argument. Otherwise, the default constructor will be invoked.

Parameters:
bean the source object
Returns:
a property editor instance or null if a property editor has not been defined or cannot be created
Since:
1.5
    public PropertyEditor createPropertyEditor(Object bean) {
        Object editor = null;
        Class cls = getPropertyEditorClass();
        if (cls != null) {
            Constructor ctor = null;
            if (bean != null) {
                try {
                    ctor = cls.getConstructor(new Class[] { Object.class });
                } catch (Exception ex) {
                    // Fall through
                }
            }
            try {
                if (ctor == null) {
                    editor = cls.newInstance();
                } else {
                    editor = ctor.newInstance(new Object[] { bean });
                }
            } catch (Exception ex) {
                // A serious error has occured.
                // Proably due to an invalid property editor.
                throw new RuntimeException("PropertyEditor not instantiated",
                                           ex);
            }
        }
        return (PropertyEditor)editor;
    }


    
Compares this PropertyDescriptor against the specified object. Returns true if the objects are the same. Two PropertyDescriptors are the same if the read, write, property types, property editor and flags are equivalent.

Since:
1.4
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj != null && obj instanceof PropertyDescriptor) {
            PropertyDescriptor other = (PropertyDescriptor)obj;
            Method otherReadMethod = other.getReadMethod();
            Method otherWriteMethod = other.getWriteMethod();
            if (!compareMethods(getReadMethod(), otherReadMethod)) {
                return false;
            }
            if (!compareMethods(getWriteMethod(), otherWriteMethod)) {
                return false;
            }
            if (getPropertyType() == other.getPropertyType() &&
                getPropertyEditorClass() == other.getPropertyEditorClass() &&
                 == other.isBound() &&  == other.isConstrained() &&
                 == other.writeMethodName &&
                 == other.readMethodName) {
                return true;
            }
        }
        return false;
    }

    
Package private helper method for Descriptor .equals methods.

Parameters:
a first method to compare
b second method to compare
Returns:
boolean to indicate that the methods are equivalent
    boolean compareMethods(Method aMethod b) {
        // Note: perhaps this should be a protected method in FeatureDescriptor
        if ((a == null) != (b == null)) {
            return false;
        }
        if (a != null && b != null) {
            if (!a.equals(b)) {
                return false;
            }
        }
        return true;
    }

    
Package-private constructor. Merge two property descriptors. Where they conflict, give the second argument (y) priority over the first argument (x).

Parameters:
x The first (lower priority) PropertyDescriptor
y The second (higher priority) PropertyDescriptor
        super(x,y);
        if (y.baseName != null) {
             = y.baseName;
        } else {
             = x.baseName;
        }
        if (y.readMethodName != null) {
             = y.readMethodName;
        } else {
             = x.readMethodName;
        }
        if (y.writeMethodName != null) {
             = y.writeMethodName;
        } else {
             = x.writeMethodName;
        }
        if (y.propertyTypeRef != null) {
             = y.propertyTypeRef;
        } else {
             = x.propertyTypeRef;
        }
        // Figure out the merged read method.
        Method xr = x.getReadMethod();
        Method yr = y.getReadMethod();
        // Normally give priority to y's readMethod.
        try {
            if (yr != null && yr.getDeclaringClass() == getClass0()) {
                setReadMethod(yr);
            } else {
                setReadMethod(xr);
            }
        } catch (IntrospectionException ex) {
            // fall through
        }
        // However, if both x and y reference read methods in the same class,
        // give priority to a boolean "is" method over a boolean "get" method.
        if (xr != null && yr != null &&
                   xr.getDeclaringClass() == yr.getDeclaringClass() &&
                   getReturnType(getClass0(), xr) == boolean.class &&
                   getReturnType(getClass0(), yr) == boolean.class &&
                   xr.getName().indexOf(.) == 0 &&
                   yr.getName().indexOf(.) == 0) {
            try {
                setReadMethod(xr);
            } catch (IntrospectionException ex) {
                // fall through
            }
        }
        Method xw = x.getWriteMethod();
        Method yw = y.getWriteMethod();
        try {
            if (yw != null && yw.getDeclaringClass() == getClass0()) {
                setWriteMethod(yw);
            } else {
                setWriteMethod(xw);
            }
        } catch (IntrospectionException ex) {
            // Fall through
        }
        if (y.getPropertyEditorClass() != null) {
        } else {
        }
         = x.bound | y.bound;
         = x.constrained | y.constrained;
    }
    /*
     * Package-private dup constructor.
     * This must isolate the new object from any changes to the old object.
     */
        super(old);
         = old.propertyTypeRef;
         = old.readMethodRef;
         = old.writeMethodRef;
         = old.propertyEditorClassRef;
         = old.writeMethodName;
         = old.readMethodName;
         = old.baseName;
         = old.bound;
         = old.constrained;
    }

    
Returns the property type that corresponds to the read and write method. The type precedence is given to the readMethod.

Returns:
the type of the property descriptor or null if both read and write methods are null.
Throws:
IntrospectionException if the read or write method is invalid
    private Class findPropertyType(Method readMethodMethod writeMethod)
        throws IntrospectionException {
        Class propertyType = null;
        try {
            if (readMethod != null) {
                Class[] params = getParameterTypes(getClass0(), readMethod);
                if (params.length != 0) {
                    throw new IntrospectionException("bad read method arg count: "
                                                     + readMethod);
                }
                propertyType = getReturnType(getClass0(), readMethod);
                if (propertyType == .) {
                    throw new IntrospectionException("read method " +
                                        readMethod.getName() + " returns void");
                }
            }
            if (writeMethod != null) {
                Class params[] = getParameterTypes(getClass0(), writeMethod);
                if (params.length != 1) {
                    throw new IntrospectionException("bad write method arg count: "
                                                     + writeMethod);
                }
                if (propertyType != null && propertyType != params[0]) {
                    throw new IntrospectionException("type mismatch between read and write methods");
                }
                propertyType = params[0];
            }
        } catch (IntrospectionException ex) {
            throw ex;
        }
        return propertyType;
    }


    
Returns a hash code value for the object. See java.lang.Object.hashCode() for a complete description.

Returns:
a hash code value for this object.
Since:
1.5
    public int hashCode() {
        int result = 7;
        result = 37 * result + ((getPropertyType() == null) ? 0 :
                                getPropertyType().hashCode());
        result = 37 * result + ((getReadMethod() == null) ? 0 :
                                getReadMethod().hashCode());
        result = 37 * result + ((getWriteMethod() == null) ? 0 :
                                getWriteMethod().hashCode());
        result = 37 * result + ((getPropertyEditorClass() == null) ? 0 :
                                getPropertyEditorClass().hashCode());
        result = 37 * result + (( == null) ? 0 :
                                .hashCode());
        result = 37 * result + (( == null) ? 0 :
                                .hashCode());
        result = 37 * result + getName().hashCode();
        result = 37 * result + (( == false) ? 0 : 1);
        result = 37 * result + (( == false) ? 0 : 1);
        return result;
    }
    // Calculate once since capitalize() is expensive.
    String getBaseName() {
        if ( == null) {
             = NameGenerator.capitalize(getName());
        }
        return ;
    }
    /*
    public String toString() {
        String message = "name=" + getName();
        message += ", class=" + getClass0();
        message += ", type=" + getPropertyType();
        message += ", writeMethod=";
        message += writeMethodName;
        message += ", readMethod=";
        message += readMethodName;
        message += ", bound=" + bound;
        message += ", constrained=" + constrained;
        return message;
    }
    */
New to GrepCode? Check out our FAQ X