Example usage for java.lang.reflect Field getDeclaringClass

List of usage examples for java.lang.reflect Field getDeclaringClass

Introduction

In this page you can find the example usage for java.lang.reflect Field getDeclaringClass.

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the field represented by this Field object.

Usage

From source file:net.java.sip.communicator.impl.protocol.jabber.InfoRetreiver.java

/**
 * Load VCard for the given user./*from  w w  w. j  a  va  2  s.co m*/
 * Using the specified timeout.
 *
 * @param vcard VCard
 * @param connection XMPP connection
 * @param user the user
 * @param timeout timeout in second
 * @throws XMPPException if something went wrong during VCard loading
 */
public void load(VCard vcard, Connection connection, String user, long timeout) throws XMPPException {
    vcard.setTo(user);

    vcard.setType(IQ.Type.GET);
    PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(vcard.getPacketID()));
    connection.sendPacket(vcard);

    VCard result = null;
    try {
        result = (VCard) collector.nextResult(timeout);

        if (result == null) {
            String errorMessage = "Timeout getting VCard information";
            throw new XMPPException(errorMessage,
                    new XMPPError(XMPPError.Condition.request_timeout, errorMessage));
        }

        if (result.getError() != null) {
            throw new XMPPException(result.getError());
        }
    } catch (ClassCastException e) {
        logger.error("No vcard for " + user);
    }

    if (result == null)
        result = new VCard();

    // copy loaded vcard fields in the supplied one.
    Field[] fields = VCard.class.getDeclaredFields();
    for (Field field : fields) {
        if (field.getDeclaringClass() == VCard.class && !Modifier.isFinal(field.getModifiers())) {
            try {
                field.setAccessible(true);
                field.set(vcard, field.get(result));
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Cannot set field:" + field, e);
            }
        }
    }
}

From source file:richtercloud.reflection.form.builder.fieldhandler.NumberFieldHandler.java

@Override
public Pair<JComponent, ComponentHandler<?>> handle0(Field field, Object instance,
        final FieldUpdateListener<FieldUpdateEvent<Number>> updateListener,
        ReflectionFormBuilder reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException {
    Type fieldType = field.getType();
    Number fieldValue = (Number) field.get(instance);
    return this.numberTypeHandler.handle(fieldType, fieldValue, field.getName(), //fieldName,
            field.getDeclaringClass(), //declaringClass
            updateListener, reflectionFormBuilder);
}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Checks if a field of a class is describeable or not e.g. static or
 * transient fields are not described.//  ww  w. jav  a 2 s .  c  o  m
 * 
 * @param type
 *            the Class holding the field
 * @param field
 *            the field to check
 * @return true if the field should be described
 */
private boolean isDescribeable(final Class<?> type, final Field field) {
    boolean isDescribeable = true;
    Class<?> declaringClass = field.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (Modifier.isStatic(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(field.getModifiers())) {
        isDescribeable &= false;
    }
    if (field.isSynthetic()) {
        isDescribeable &= false;
    }
    return isDescribeable;
}

From source file:richtercloud.reflection.form.builder.fieldhandler.BooleanFieldHandler.java

@Override
public JComponent handle(Field field, Object instance,
        final FieldUpdateListener<FieldUpdateEvent<Boolean>> updateListener,
        ReflectionFormBuilder reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException {
    Type fieldType = field.getType();
    Boolean fieldValue = (Boolean) field.get(instance);
    return this.booleanTypeHandler.handle(fieldType, fieldValue, field.getName(), //fieldName,
            field.getDeclaringClass(), //declaringClass
            updateListener, reflectionFormBuilder).getKey();
}

From source file:richtercloud.reflection.form.builder.fieldhandler.AbstractListFieldHandler.java

@Override
public JComponent handle(Field field, Object instance, FieldUpdateListener<E> updateListener,
        R reflectionFormBuilder) throws IllegalArgumentException, IllegalAccessException,
        FieldHandlingException, InstantiationException, InvocationTargetException {
    Type fieldGenericType = field.getGenericType();
    Pair<JComponent, ComponentHandler<?>> retValue = this.typeHandler.handle(fieldGenericType,
            (T) field.get(instance), //fieldValue
            field.getName(), field.getDeclaringClass(), //declaringClass
            updateListener, reflectionFormBuilder);
    return retValue.getKey();
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

public String getCSVLabel() {
    StringBuffer sb = new StringBuffer();
    Field[] flds = this.getClass().getDeclaredFields();
    for (Field fld : flds) {
        try {/*www. j  a va 2 s .  c om*/
            if (fld.getDeclaringClass().equals(this.getClass())) {
                sb.append(fld.getName());
                sb.append(",");
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
    return sb.toString();
}

From source file:org.nuunframework.cli.NuunCliPlugin.java

private Map<Class<?>, Options> createOptions(Collection<Class<?>> collection) {
    Set<String> shortOptions = Sets.newHashSet();
    Set<String> longOptions = Sets.newHashSet();

    Map<Class<?>, Options> optionsMap = Maps.newHashMap();

    for (Class<?> class1 : collection) {
        logger.info("CLASS " + class1.getSimpleName());
        Set<Field> fields = annotatedFields(class1, NuunOption.class);
        Options internalOptions = new Options();
        for (Field field : fields) {
            logger.info("Class : " + field.getDeclaringClass().getSimpleName() + " / " + field.getName());
            Option option = createOptionFromField(field);

            if (!Strings.isNullOrEmpty(option.getOpt()) && shortOptions.contains(option.getOpt())) {
                exception("Short option " + option.getOpt() + " already exists!");
            }/*from   w w  w.  j  a va2s . c o m*/

            if (!Strings.isNullOrEmpty(option.getLongOpt()) && longOptions.contains(option.getLongOpt())) {
                exception("Long option " + option.getLongOpt() + " already exists!");
            }

            if (Strings.isNullOrEmpty(option.getOpt()) && Strings.isNullOrEmpty(option.getLongOpt())) {
                exception("NuunOption defined on " + field + " has no opt nor longOpt.");
            }

            internalOptions.addOption(option);
            // global one
            optionsAggregated.addOption(option);

            shortOptions.add(option.getOpt());
            longOptions.add(option.getLongOpt());
        }

        optionsMap.put(class1, internalOptions);

    }

    return optionsMap;
}

From source file:org.kchine.r.tools.wsmapper.Globals.java

public static void generateS4BeanRef() throws Exception {

    for (Iterator<?> iter = DirectJNI._s4BeansHash.keySet().iterator(); iter.hasNext();) {

        String className = (String) iter.next();

        Field[] fields = DirectJNI._s4BeansHash.get(className).getDeclaredFields();
        final String rclass = DirectJNI._s4BeansMappingRevert.get(className);

        final String[][] slotsContainer = new String[1][];
        org.kchine.r.server.DirectJNI.getInstance().runR(new org.kchine.r.server.ExecutionUnit() {
            public void run(org.rosuda.JRI.Rengine e) {
                long slotsId = e.rniEval(e.rniParse("getSlots(\"" + rclass + "\")", 1), 0);
                slotsContainer[0] = e.rniGetStringArray(e.rniGetAttr(slotsId, "names"));
            }//from   www .j ava  2s.c om
        });

        String classShortName = className.substring(className.lastIndexOf('.') + 1);

        String outputFileName = Globals.GEN_ROOT_SRC + Globals.FILE_SEPARATOR
                + className.replace('.', Globals.FILE_SEPARATOR) + "Ref" + ".java";
        new File(outputFileName.substring(0, outputFileName.lastIndexOf(FILE_SEPARATOR))).mkdirs();

        log.info("output file:" + outputFileName);
        PrintWriter outputWriter = new PrintWriter(outputFileName);

        outputWriter.println("package " + className.substring(0, className.lastIndexOf('.')) + ";");
        outputWriter.println("public class " + classShortName + "Ref" + " extends " + classShortName
                + " implements org.kchine.r.server.ReferenceInterface, java.io.Externalizable {");

        outputWriter.println("private long[] _rObjectIdHolder;\n");
        outputWriter.println("private String _slotsPath;\n");
        outputWriter.println("private org.kchine.r.server.AssignInterface _assignInterface;\n");
        outputWriter.println("public long getRObjectId() {");
        outputWriter.println("   return _rObjectIdHolder[0];");
        outputWriter.println("}\n");
        outputWriter.println("public String getSlotsPath() {");
        outputWriter.println("     return _slotsPath;");
        outputWriter.println("}\n");

        outputWriter.println(
                "public void setAssignInterface(org.kchine.r.server.AssignInterface assignInterface) {");
        outputWriter.println("     _assignInterface=assignInterface;");
        outputWriter.println("}\n");
        outputWriter.println("public org.kchine.r.server.AssignInterface getAssignInterface() {");
        outputWriter.println("   return _assignInterface;");
        outputWriter.println("}\n");

        outputWriter.println(
                "\npublic org.kchine.r.RObject extractRObject() {try {return _assignInterface.getObjectFromReference(this);} catch (java.rmi.RemoteException re) {throw new RuntimeException(org.kchine.r.server.Utils.getStackTraceAsString(re));}}\n");

        String nullifyFields = "";
        for (int i = 0; i < fields.length; ++i)
            nullifyFields += "super.set" + Utils.captalizeFirstChar(fields[i].getName()) + "(null);";
        outputWriter.println("public " + classShortName + "Ref " + "(){ super(); _rObjectIdHolder=new long[1];"
                + nullifyFields + " };");
        outputWriter.println("public " + classShortName + "Ref "
                + "(long rObjectId, String slotsPath){ super(); _rObjectIdHolder=new long[1]; _rObjectIdHolder[0]=rObjectId; _slotsPath=slotsPath; "
                + nullifyFields + "};");
        outputWriter.println("public " + classShortName + "Ref "
                + "(long[] rObjectIdHolder, String slotsPath){ super(); _rObjectIdHolder=rObjectIdHolder; _slotsPath=slotsPath; "
                + nullifyFields + "};");

        for (int i = 0; i < fields.length; ++i) {
            Field f = fields[i];
            String getterName = (f.getType().equals(boolean.class) || f.getType().equals(Boolean.class) ? "is"
                    : "get") + Utils.captalizeFirstChar(f.getName());
            String setterName = "set" + Utils.captalizeFirstChar(f.getName());

            if (f.getDeclaringClass().getName().equals(className)) {
                outputWriter
                        .print("\n public " + "void " + setterName + "(" + f.getType().getName() + " p0" + ")");
                outputWriter.print("{ " + "if ( p0 instanceof org.kchine.r.server.ReferenceInterface ) {"
                        + "super." + setterName + "(p0);" + "} else "
                        + "   {try {_rObjectIdHolder[0]=_assignInterface.assign(_rObjectIdHolder[0],_slotsPath+\"@\"+\""
                        + slotsContainer[0][i] + "\",p0);} \n catch (Exception ex) {ex.printStackTrace();}}"
                        + " }\n");
                outputWriter.print("\n public " + f.getType().getName() + " " + getterName + "(){");

                if (!DirectJNI._abstractFactories.contains(f.getType().getName())) {

                    outputWriter.print("if (super." + getterName + "()==null){ ");
                    outputWriter.print(f.getType().getName() + "Ref" + " result=new " + f.getType().getName()
                            + "Ref(_rObjectIdHolder,_slotsPath+\"@\"+\"" + slotsContainer[0][i]
                            + "\"); result.setAssignInterface(_assignInterface); " + "super." + setterName
                            + "(result);" + "} return " + "super." + getterName + "();");
                } else {
                    outputWriter.print(" return null;/* !!!!!! to be changed */ ");
                }
                outputWriter.print("}");

            }
        }

        outputWriter.println(

                "public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException {"
                        + "   out.writeLong(_rObjectIdHolder[0]);" + "   out.writeUTF(_slotsPath);"
                        + "   out.writeObject(_assignInterface);");

        if (true) {

            outputWriter.print("java.lang.reflect.Field[] fields= " + classShortName
                    + ".class.getDeclaredFields();"
                    + "java.util.Vector<java.lang.reflect.Field> nonNullFields=new java.util.Vector<java.lang.reflect.Field>();"
                    + "for (int i=0;i<fields.length;++i) fields[i].setAccessible(true);" + "try {"

                    + "   for (int i=0;i<fields.length;++i) {"
                    + "org.kchine.r.server.ReferenceInterface fValue=(org.kchine.r.server.ReferenceInterface)fields[i].get(this);"
                    + "if ( fValue!= null && (!fValue.getAssignInterface().equals(_assignInterface) || fValue.getRObjectId()!=_rObjectIdHolder[0] ||  org.kchine.r.server.DirectJNI.hasDistributedReferences(fValue)) ) {"
                    + "   nonNullFields.add(fields[i]);" + "}}" + "   out.writeInt(nonNullFields.size());"
                    + "   for (java.lang.reflect.Field f:nonNullFields) {" + "      out.writeUTF(f.getName());"
                    + "       out.writeObject(f.get(this));" + "   }" + "}" + "catch (Exception e) {"
                    + "   e.printStackTrace();"
                    + "} finally {for (int i=0;i<fields.length;++i) fields[i].setAccessible(false);}");

        } else {
            outputWriter.print("int counter=0;");
            for (int i = 0; i < fields.length; ++i) {
                outputWriter.print(" if (super.get" + Utils.captalizeFirstChar(fields[i].getName())
                        + "()!=null) ++counter;");
            }
            outputWriter.println("out.writeInt(counter);");
            for (int i = 0; i < fields.length; ++i) {
                Field f = fields[i];
                outputWriter.print(" if (super.get" + Utils.captalizeFirstChar(f.getName()) + "()!=null) {");
                outputWriter.print(" out.writeUTF(\"" + f.getName() + "\");");
                outputWriter.print(" out.writeObject(super."
                        + (f.getType().equals(boolean.class) || f.getType().equals(Boolean.class) ? "is"
                                : "get")
                        + Utils.captalizeFirstChar(f.getName()) + "());}");

            }
        }

        outputWriter.println("}");
        outputWriter.println(
                "public void readExternal(java.io.ObjectInput in) throws java.io.IOException, ClassNotFoundException {"
                        + "   _rObjectIdHolder[0]=in.readLong();" + "   _slotsPath=in.readUTF();"
                        + "   _assignInterface=(org.kchine.r.server.AssignInterface)in.readObject();");

        outputWriter.println("int counter=in.readInt();  if (counter>0) {");
        outputWriter.println("try { for (int i=0; i<counter; ++i) {String fname=in.readUTF();");
        outputWriter.println("java.lang.reflect.Field f=" + classShortName + ".class.getDeclaredField(fname);");
        outputWriter.println("f.setAccessible(true);");
        outputWriter.println("f.set(this, in.readObject());");
        outputWriter.println("f.setAccessible(false);");

        // outputWriter.println("java.lang.reflect.Method
        // setter="+classShortName
        // +".class.getMethod(\"set\"+util.Utils.captalizeFirstChar(fname),
        // new Class[]{f.getType()} );");
        // outputWriter.println("setter.invoke(this, new
        // Object[]{in.readObject()}); "

        outputWriter.println("  }} catch (Exception e) {e.printStackTrace();} ");

        outputWriter.println("}");
        outputWriter.println("}");

        outputWriter.println("public String toString() {" + "StringBuffer result=new StringBuffer();" + "try {"
                + "result.append(\"A Reference to an object of Class \\\"" + classShortName
                + "\\\" on the R servant "
                + "<\"+_assignInterface.getName()+\">  [\"+_rObjectIdHolder[0]+\"/\"+_slotsPath+\"]\\n\");");
        for (int i = 0; i < fields.length; ++i) {
            Field f = fields[i];

            outputWriter.print("result.append(" + "\"Field \\\"" + f.getName() + "\\\":\\n\");");
            outputWriter.print("if (super.get" + Utils.captalizeFirstChar(f.getName())
                    + "()!=null) result.append(org.kchine.r.server.Utils.indent (super.get"
                    + Utils.captalizeFirstChar(f.getName()) + "().toString(),1)); "
                    + "else result.append(\"null(\"+_rObjectIdHolder[0]+\"@" + slotsContainer[0][i]
                    + ")\\n\");");
        }
        outputWriter.println("} catch (java.rmi.RemoteException e) {e.printStackTrace();}"
                + "return result.toString();" + "}");

        outputWriter.println("public boolean equals(Object inputObject) {");
        outputWriter.println("if (inputObject==null || !(inputObject instanceof " + classShortName + "Ref"
                + ")) return false;");
        outputWriter.println("return  ((" + classShortName + "Ref)"
                + "inputObject)._assignInterface.equals( _assignInterface ) && ((" + classShortName + "Ref"
                + ")inputObject)._rObjectIdHolder[0]==_rObjectIdHolder[0] && ((" + classShortName + "Ref"
                + ")inputObject)._slotsPath.equals(_slotsPath);");
        outputWriter.println("}");

        outputWriter.println("}");
        outputWriter.close();

        String objectNameOutputFileName = Globals.GEN_ROOT_SRC + Globals.FILE_SEPARATOR
                + className.replace('.', Globals.FILE_SEPARATOR) + "ObjectName" + ".java";
        PrintWriter objectNameOutputWriter = new PrintWriter(objectNameOutputFileName);

        objectNameOutputWriter.println("package " + className.substring(0, className.lastIndexOf('.')) + ";");
        objectNameOutputWriter.println("import org.kchine.r.*;");
        objectNameOutputWriter.println("public class " + classShortName + "ObjectName" + " extends "
                + classShortName + " implements org.kchine.r.ObjectNameInterface {");
        objectNameOutputWriter.println("private String _name; private String _env;");
        objectNameOutputWriter.println("public String getRObjectName() {return _name;}");
        objectNameOutputWriter.println("public void setRObjectName(String _name) {this._name = _name;}");
        objectNameOutputWriter.println("public String getRObjectEnvironment() {return _env;}");
        objectNameOutputWriter.println("public void setRObjectEnvironment(String _env) {this._env = _env;}");

        objectNameOutputWriter.println("public boolean equals(Object obj) {");
        objectNameOutputWriter
                .println("   if (obj == null || !(obj instanceof ObjectNameInterface) )   return false;");
        objectNameOutputWriter.println(
                "   return (((ObjectNameInterface) obj).getRObjectName().equals(this._name)) && (((ObjectNameInterface) obj).getRObjectEnvironment().equals(_env));");
        objectNameOutputWriter.println("}");

        objectNameOutputWriter.println("public String toString() {");
        objectNameOutputWriter
                .println("   return \"" + classShortName + "ObjectName" + ":\"+_env+\"$\"+_name;");
        objectNameOutputWriter.println("}");

        objectNameOutputWriter.println("public void writeExternal(java.io.ObjectOutput out)");
        objectNameOutputWriter.println("    throws java.io.IOException {");
        objectNameOutputWriter.println("   out.writeUTF(_env);");
        objectNameOutputWriter.println("   out.writeUTF(_name);");
        objectNameOutputWriter.println("}");

        objectNameOutputWriter.println("public void readExternal(java.io.ObjectInput in)");
        objectNameOutputWriter.println("    throws java.io.IOException, ClassNotFoundException {");
        objectNameOutputWriter.println("   _env=in.readUTF();");
        objectNameOutputWriter.println("   _name=in.readUTF();");
        objectNameOutputWriter.println("}");

        objectNameOutputWriter.println("}");
        objectNameOutputWriter.close();

    }

}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public boolean hasConsistencyAnnotation(Field field) {
    log.debug("Check @Consistency annotation on field {} of class {}", field.getName(),
            field.getDeclaringClass().getCanonicalName());

    boolean consistency = false;
    if (field.getAnnotation(Consistency.class) != null) {
        consistency = true;/*from w  w w.  ja v  a2  s .  c o m*/
    }
    return consistency;
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

public String toCSV() {
    StringBuffer sb = new StringBuffer();
    Field[] flds = this.getClass().getDeclaredFields();
    for (Field fld : flds) {
        try {//www  .j  a v a  2  s  .  c  o  m
            fld.setAccessible(true);
            if (fld.getDeclaringClass().equals(this.getClass()) && (fld.get(this) != null)) {
                sb.append(fld.get(this).toString());
            }
            sb.append(",");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}