私はCで行ったように、javaで一般的な拡張メソッドを実装したいと思っています。ここでC#のようにJavaで汎用拡張メソッドを作成するには?
は、私のC#のコードです:
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;
}
}
:ここ
DataRecordExtensions.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メソッドを使用する方法でありますあなたが見ることができると同様
、私は今、私は、Javaでこのようなものを使用したいcountriesReader.Get <文字列>(「CountryID」) を使用しています。このような拡張メソッドをJavaで使用するにはどうすればよいですか、それとも何か別の方法がありますか? Javaを使用し
あなたはJavaのジェネリックについて何を検索しましたか? – Omore
代わりに、GroovyとKotlinがあります。 – chrylis
私はJavaが拡張メソッドと同等の機能を持っているとは思わない。 – juharr