2016-05-17 135 views
0

我有一個簡單的通用靜態方法在Java中失敗了一個具有私有構造函數的類。這裏的方法:通用斷言失敗

public static <E> void assertThatCtorIsPrivate(Class<E> clazz, Class<?>... parameters) throws NoSuchMethodException, InstantiationException, IllegalAccessException { 
    Preconditions.checkNotNull(clazz); 
    final Constructor<?> constructor = clazz.getConstructor(parameters); 
    constructor.setAccessible(true); 
    try { 
     constructor.newInstance((Object[]) null); 
    } catch(InvocationTargetException e) { 
     if(e.getCause() instanceof UnsupportedOperationException) { 
      throw new UnsupportedOperationException(); 
     } 
    } finally { 
     constructor.setAccessible(false); 
    } 

    assert Modifier.isPrivate(constructor.getModifiers()); 
} 

下面是我想測試類:

import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 

import com.google.common.base.Preconditions; 
import com.google.gson.Gson; 

public final class DecodeJson { 

    private static final Gson GSON = new Gson(); 

    private DecodeJson() { 
     throw new UnsupportedOperationException(); 
    } 

    public static <E> E parse(final File file, Class<E> clazz) throws IOException { 
     Preconditions.checkNotNull(file); 
     Preconditions.checkArgument(file.exists() && file.canRead()); 
     return GSON.fromJson(new FileReader(file), clazz); 
    } 

    public static <E> E parse(final String content, Class<E> clazz) throws IOException { 
     Preconditions.checkNotNull(content); 
     Preconditions.checkArgument(content.length() != 0); 
     return GSON.fromJson(content, clazz); 
    } 

} 

在我的單元測試,我只是有:

@Test(expected = UnsupportedOperationException.class) 
public void testPrivateCtor() throws NoSuchMethodException, InstantiationException, IllegalAccessException { 
    ReflectionHelper.assertThatCtorIsPrivate(DecodeJson.class); 
} 

我得到一個NoSuchMethodException當我打電話final Constructor<?> constructor = clazz.getConstructor(parameters);。我已經嘗試用?代替E,但仍然沒有骰子。任何見解?

+0

你想在這裏證明什麼?你能不能讓課堂本身變成靜態的? –

+0

@MarkChorley Java中的頂級類不能是靜態的。這是看到100%的代碼覆蓋率,所以我得到了溫暖,模糊的感覺。 – djthoms

回答

2

Class.getConstructor(Class<?>... parameterTypes)只會返回可訪問的構造函數。

A private構造函數肯定不能從外部訪問。

要獲得不可訪問的構造函數,請使用Class.getDeclaredConstructor(Class<?>... parameterTypes)

+0

啊......我想這是關注細節的關鍵時刻之一。謝謝! – djthoms