Java tutorial
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwt.json.serialization; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.JField; import com.google.gwt.core.ext.typeinfo.JType; import com.google.gwt.core.ext.typeinfo.NotFoundException; import org.apache.commons.lang3.StringUtils; import java.util.HashSet; import java.util.Set; /** * @author andrii borovyk 28.12.2015 */ public class AccessorResolveUtil { public static FieldInfo resolveAccessor(JField jField, JClassType jClassType) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.setjField(jField); populateSetAccessor(jField, jClassType, fieldInfo); populateGetAccessor(jField, jClassType, fieldInfo); return fieldInfo; } private static void populateSetAccessor(JField jField, JClassType jClassType, FieldInfo fieldInfo) { String accessorName = "set" + StringUtils.capitalize(jField.getName()); JType[] types = new JType[1]; types[0] = jField.getType(); try { jClassType.getMethod(accessorName, types); fieldInfo.setSetAccessorName(accessorName); } catch (NotFoundException e) { //ignore } } private static void populateGetAccessor(JField jField, JClassType jClassType, FieldInfo fieldInfo) { String accessorName = "get" + StringUtils.capitalize(jField.getName()); try { jClassType.getMethod(accessorName, new JType[0]); fieldInfo.setGetAccessorName(accessorName); } catch (NotFoundException e) { //try 'is' accessor if (jField.getType().getQualifiedSourceName().equals(Boolean.class.getName()) || jField.getType().getQualifiedSourceName().equals("boolean")) { accessorName = "is" + StringUtils.capitalize(jField.getName()); try { jClassType.getMethod(accessorName, new JType[0]); fieldInfo.setGetAccessorName(accessorName); } catch (NotFoundException ex) { //ignore } } } } public static Set<JField> resolveFieldCandidates(JClassType jClassType) { Set<JField> candidates = new HashSet<JField>(); fillCandidateFields(jClassType, candidates); return candidates; } protected static void fillCandidateFields(JClassType jClassType, Set<JField> fields) { Serializable annotation = jClassType.getAnnotation(Serializable.class); if (annotation == null) { return; } JField[] jFields = jClassType.getFields(); for (JField jField : jFields) { if (!jField.isTransient()) { fields.add(jField); } } fillCandidateFields(jClassType.getSuperclass(), fields); } }