如何在Java中像在C#中一样创建泛型扩展方法?
我想在java中实现一个通用的扩展方法,就像在c#中一样
以下是我的C#代码:
数据记录扩展。cs
public static class DataRecordExtensions
{
public static T Get<T>(this IDataRecord record, string fieldName, T defaultVal = default(T))
{
object o = record[fieldName];
if (o != null && !DBNull.Value.Equals(o))
{
try
{
return (T)Convert.ChangeType(o, typeof(T));
}
catch
{
}
}
return defaultVal;
}
}
下面是我如何使用DataRecordExtensions方法:
CountryRepository。cs
public class CountryRepository : ICountryRepository
{
// ... here are some code not relevant to understand my problem
public IEnumerable<Country> LoadCountries()
{
List<Country> countries = new List<Country>();
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.Open();
string sqlTxt = "SELECT * FROM tab_Countries ORDER BY SortID";
using (SqlCommand readCmd = new SqlCommand(sqlTxt, sqlConnection))
{
SqlDataReader countriesReader = readCmd.ExecuteReader();
while (countriesReader.Read())
{
Country c = new Country();
c.CountryCode = countriesReader.Get<string>("CountryID");
c.Country = countriesReader.Get<string>("Country");
c.SortID = countriesReader.Get<int>("SortID");
countries.Add(c);
}
readCmd.Dispose();
countriesReader.Dispose();
};
sqlConnection.Close();
}
return countries;
}
}
正如你所看到的,我使用countriesReader。获取<;字符串>;(“CountryID”) 现在我想在Java中使用类似的东西。我如何在Java中使用这样的扩展方法,或者有其他替代方法吗
共 (0) 个答案