泛型方法(跟类没关系)
public <T> void add(T t){
System.out.println(t.toString());
}
public <T extends View> T obtainView(Class<T> t,int resId) throws InstantiationException, IllegalAccessException{
return t.newInstance();
}
private static <T> T test(Class<T> class1) {
try {
return class1.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
泛型类(android的适配器)
public class ArrayAdapter<T> extends BaseAdapter implements Filterable {
private List<T> mObjects;
private ArrayList<T> mOriginalValues;
public ArrayAdapter(Context context, int resource, T[] objects) {
init(context, resource, 0, Arrays.asList(objects));
}
public void add(T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(object);
} else {
mObjects.add(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* {@inheritDoc}
*/
public int getCount() {
return mObjects.size();
}
/**
* {@inheritDoc}
*/
public T getItem(int position) {
return mObjects.get(position);
}
/**
* Returns the position of the specified item in the array.
*
* @param item The item to retrieve the position of.
*
* @return The position of the specified item.
*/
public int getPosition(T item) {
return mObjects.indexOf(item);
}
/**
* {@inheritDoc}
*/
public long getItemId(int position) {
return position;
}
/**
* {@inheritDoc}
*/
public View getView(int position, View convertView, ViewGroup parent) {
return createViewFromResource(position, convertView, parent, mResource);
}
.............................
.................................
...................................
}
泛型类+泛型接口
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 com.jytnn.utils;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Implementations of this interface convert ResultSets into other objects.
*
* @param <T> the target type the input ResultSet will be converted to.
*/
public interface ResultSetHandler<T> {
/**
* Turn the <code>ResultSet</code> into an Object.
*
* @param rs The <code>ResultSet</code> to handle. It has not been touched
* before being passed to this method.
*
* @return An Object initialized with <code>ResultSet</code> data. It is
* legal for implementations to return <code>null</code> if the
* <code>ResultSet</code> contained 0 rows.
*
* @throws SQLException if a database access error occurs
*T可以使普通object也可以使数组List<T>
*/
T handle(ResultSet rs) throws SQLException;
}
实现泛型接口
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 com.jytnn.utils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* <code>ResultSetHandler</code> implementation that converts a
* <code>ResultSet</code> into a <code>List</code> of beans. This class is
* thread safe.
*
* @param <T> the target bean type
* @see org.apache.commons.dbutils.ResultSetHandler
*/
public class BeanListHandler<T> implements ResultSetHandler<List<T>> {
private ResultSetParser<T> resultSetParser;
/**
* Creates a new instance of BeanListHandler.
*
* @param type The Class that objects returned from <code>handle()</code>
* are created from.
*/
public BeanListHandler(Class<T> type) {
resultSetParser = new ResultSetParser<T>(type);
}
/**
* Convert the whole <code>ResultSet</code> into a List of beans with
* the <code>Class</code> given in the constructor.
*
* @param rs The <code>ResultSet</code> to handle.
*
* @return A List of beans, never <code>null</code>.
*
* @throws SQLException if a database access error occurs
* @see org.apache.commons.dbutils.RowProcessor#toBeanList(ResultSet, Class)
*/
public List<T> handle(ResultSet rs) throws SQLException {
return resultSetParser.toBeanList(rs);
}
}
工具类,解析类
package com.jytnn.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ResultSetParser<T> {
/**
* Student.class
*/
private Class<T> type;
public ResultSetParser(Class<T> type) {
this.type=type;
}
public List<T> toBeanList(ResultSet resultSet){
ArrayList<T> arrayList2 = new ArrayList<T>();
try {
Field[] fields = type.getDeclaredFields();
ArrayList<String> arrayList = new ArrayList<String>();
for (Field field : fields) {
arrayList.add(field.getName());
}
Method[] methods = type.getDeclaredMethods();
HashMap<String, Method> hashMap = new HashMap<String, Method>();
for (Method method : methods) {
hashMap.put(method.getName(), method);
}
while (resultSet.next()) {
T newInstance = type.newInstance();
for (String fieldName : arrayList) {
Object object = resultSet.getObject(fieldName);
Method method = hashMap.get("set"+wordFirstToUpper(fieldName));
if(object!=null && method!=null){
Class<?>[] parameterTypes = method.getParameterTypes();
if(parameterTypes.length==1
&¶meterTypes[0].getName().equals(object.getClass().getName())){
method.invoke(newInstance, object);
}
}
}
arrayList2.add(newInstance);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return arrayList2;
}
public static String wordFirstToUpper(String word) {
int c = word.charAt(0);
if (c >= 97 && c <= 122) {
c -= 32;
}
return String.format("%c%s", c, word.substring(1));
}
}
使用方法:
public List<Student> query() throws SQLException{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from stu");
List<Student> handle = new BeanListHandler<Student>(Student.class).handle(resultSet);
statement.close();
connection.close();
return handle;
}