如何在Java中像在C#中一样创建泛型扩展方法?

amrnrhlw  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(121)

我想在Java中实现一个通用的扩展方法,就像我在C#中做的那样。
以下是我的C#代码:

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方法:

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.Get< string >(“CountryID”)**现在我想在Java中使用这样的东西。我如何在Java中使用这样的扩展方法,或者有其他选择吗?

0h4hbjxa

0h4hbjxa1#

在Java中,你也可以这样调用一个方法。

private FileConfiguration config = ....
public <T> T getFromConfig(String path) {
    return (T) config.get(path);
}

字符串
它可以被称为

String bar = Foo.<String>getFromConfig(Some.File.Path);

相关问题