如何指定字体属性的通用Map?

5Yr*_*DBA 4 java generics

我有这个方法jdk1.6抱怨(没有错误只是警告)关于泛型类型参数化没有在Map和...中使用:

public static Font getStrikethroughFont(String name, int properties, int size)
    {
        Font font = new Font(name, properties, size); 

        Map  attributes = font.getAttributes(); 
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
        Font newFont = new Font(attributes); 
        return newFont;             
    }
Run Code Online (Sandbox Code Playgroud)

然后我改为以下内容:

public static Font getStrikethroughFont2(String name, int properties, int size)
    {
        Font font = new Font(name, properties, size); 

        Map<TextAttribute, ?>  attributes = font.getAttributes(); 
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
        Font newFont = new Font(attributes); 
        return newFont;             
    }
Run Code Online (Sandbox Code Playgroud)

但是

attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
Run Code Online (Sandbox Code Playgroud)

声明不再有效.

TextAttribute.STRIKETHROUGH_ON 是一个布尔值.

如何在上述方法中使用Generic Type功能?我查看了核心Java书籍,但未找到答案.有人可以帮帮我吗?

jjn*_*guy 9

你应该使用的是font.deriveFont(map).

public static Font getStrikethroughFont2(String name, int properties, int size)
{
   Font font = new Font(name, properties, size); 
   Map<TextAttribute, Object>  attributes = new HashMap<TextAttribute, Object>();
   attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
   Font newFont = font.deriveFont(attributes);
   return newFont;             
}
Run Code Online (Sandbox Code Playgroud)

这将解决您的泛型问题.派生字体将复制旧字体,然后应用您提供的属性.因此,它将使用Font构造函数执行相同的操作.


Boz*_*zho 5

您不能put在该地图中。它仅用于阅读。

您可以用来放置属性的地图是 Map<String, Object>

如果您需要获取现有地图并使用其属性和其他属性创建字体,请使用:

Map<TextAttribute, Object> map = 
   new HashMap<TextAttribute, Object>(font.getAttributes());
Run Code Online (Sandbox Code Playgroud)