Java: newInstance of class that has no default constructor

前端 未结 6 801
广开言路
广开言路 2020-11-29 02:32

I\'m trying to build an automatic testing framework (based on jUnit, but that\'s no important) for my students\' homework. They will have to create constructors for some cla

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 03:26

    You could distribute the following source code with your assignment. Tell the students to include it in their source code. Their code won't compile unless they code an Assignment class with the proper signature. The compiler does the signaure checking for you.

    Then your testing program does not need to use reflection. Just instantiate an AssignmentFactory and call the make method with the proper arguments.

    If you use this idea, your new challenge will be some students modifying AssignmentFactory to fit their Assignment class (breaking your testing program).

    package assignment ;
    
    public class AssignmentFactory
    {
         public AssignmentFactory ( )
         {
               super ( ) ;
         }
    
         public AssignmentFactory make ( .... parameters )
         {
               return new Assignment ( .... arguments ) ;
         }
    }
    

提交回复
热议问题