logo
down
shadow

How to make a generic enum which could hold a Class<T>?


How to make a generic enum which could hold a Class<T>?

By : Imtiaz Ahmed
Date : November 14 2020, 04:48 PM
like below fixes the issue The value of an enum constant is always an object which is an instance of the enum class. You cannot make it have a different value; neither a reference to a class, nor anything else.
You can add instance fields on your enum which can hold whatever values you want for each enum constant:
code :
enum MyEnum {
    STEP(Step.class),
    FOO(Foo.class),
    BAR(Bar.class);

    public final Class<?> klass;

    private MyEnum(Class<?> klass) {
        this.klass = klass;
    }
}
method(MyEnum.STEP.klass);
class MyConstant<T> {
    public static final MyConstant<Step> STEP = new MyConstant<>();
    public static final MyConstant<Foo> FOO = new MyConstant<>();
    public static final MyConstant<Bar> BAR = new MyConstant<>();

    private MyConstant() {}
}
<T> IInterface<T> method(MyConstant<T> type)
IInterface<Step> something = method(MyConstant.STEP);
class MyConstant<T> {
    public static final MyConstant<Step> STEP = new MyConstant<>(Step.class);
    public static final MyConstant<Foo> FOO = new MyConstant<>(Foo.class);
    public static final MyConstant<Bar> BAR = new MyConstant<>(Bar.class);

    public final Class<T> klass;

    private MyConstant(Class<T> klass) {
        this.klass = klass;
    }
}


Share : facebook icon twitter icon
generic Enum.valueOf method : Enum class in parameter and return Enum item

generic Enum.valueOf method : Enum class in parameter and return Enum item


By : user2569979
Date : March 29 2020, 07:55 AM
This might help you Why implement your own, when you can use Java's own implementation for this?
code :
 YourEnum yourEnum = Enum.valueOf(YourEnum.class, value);
private static <E extends Enum<E>> E getEnum(Class<E> enumClass, String name){
    try {
        return Enum.valueOf(enumClass, name);
    } catch(IllegalArgumentException e) {
        return null;
    }
}
getEnum(Enum1.class, "A")
Any way to let an enum hold a generic object and access it later without typecasting?

Any way to let an enum hold a generic object and access it later without typecasting?


By : li-ju
Date : March 29 2020, 07:55 AM
I hope this helps you . In my app's networking class, I follow the typical closure model, in which you pass a result to a completion closure. , How about this
code :
enum Result<T> {
    case success(T)
    case failure(String)
}
class func login(username: String, password: String, completion: @escaping (Result<User>) -> Void){
    //...
    //let user = makeUserWithSomeData()
    completion(Result.success(user))
}
MyWebServices.login(username: username, password: password) {
    (result) in
    switch(result) {
    case .success(let value):
        useMyValue(user)
        break
    case .failure(let error):
        print("Error: \(error)")
        break;
    }
}
How to make a struct containing an enum generic over the enum variant?

How to make a struct containing an enum generic over the enum variant?


By : user3517562
Date : March 29 2020, 07:55 AM
Hope that helps Probably the easiest thing to do is to make Profession a trait rather than an enum, and make each Profession a unit struct:
code :
struct Human<P: ?Sized + Profession> {
  name: String,
  profession: P,
}

struct Doctor;
struct Teacher;

trait Profession {}

impl Profession for Doctor {}
impl Profession for Teacher {}

struct Family {
  family_doctor: Human<Doctor>,
}
fn into_name<P: Profession>(any_human: Human<P>) -> String {
    any_human.name
}
fn into_name_dyn(any_human: Box<Human<dyn Profession>>) -> String {
    any_human.name
}
impl<P: ?Sized + Profession> Profession for Box<P> {}

fn into_name_box(any_human: Human<Box<dyn Profession>>) -> String {
    any_human.name
}
enum SomeProfession {
    Doctor(Doctor),
    Teacher(Teacher),
}

impl Profession for SomeProfession {}

fn into_name_enum(any_human: Human<SomeProfession>) -> String {
    any_human.name
}
Can I make a Swift enum generic, so I can use its cases to infer a type for a generic class?

Can I make a Swift enum generic, so I can use its cases to infer a type for a generic class?


By : user3721474
Date : March 29 2020, 07:55 AM
I wish this helpful for you You've got it backwards, you shouldn't infer the generic type depending on the enum value, because that means you want to determine some compile-time thing (generic type) with a value that is possibly known at runtime (the value of the enum).
Therefore, we need to make the type parameter a compile-time-only thing, i.e. also a type parameter.
code :
protocol VehicleTypeProtocol {
    // this associated type creates the link between a vehicle type and a config type
    associatedtype ConfigType: Config
    // this is so that we can assign to Vehicle.type
    static var type: VehicleType { get }
}

struct Car : VehicleTypeProtocol {
    typealias ConfigType = CarConfig
    static var type: VehicleType { .car }
}

struct Bike : VehicleTypeProtocol {
    typealias ConfigType = BikeConfig
    static var type: VehicleType { .bike }
}

struct Scooter: VehicleTypeProtocol {
    typealias ConfigType = BikeConfig
    static var type: VehicleType { .scooter }
}
init<T: VehicleTypeProtocol>(type: T.Type, config: C) where T.ConfigType == C {
    self.type = T.type
    self.config = config
}
let bike = Vehicle(type: Bike.self, config: .mtb)
C++ How can I code a generic struct to hold any enum

C++ How can I code a generic struct to hold any enum


By : moquist
Date : March 29 2020, 07:55 AM
it fixes the issue I'm pretty new to C++ so apologies in advance, , What you're looking for is a union:
Related Posts Related Posts :
  • The type org.openqa.selenium.firefox.FirefoxDriver is not accessible
  • Limitations (drawbacks) of java programming language?
  • Error: ')' expected Error: illegal start of expression
  • TableRowSorter use LookAndFeel of TableHeader, but own Comparator
  • Difference between @GeneratedValue and @GenericGenerator
  • Design Scenario: Smartphone class and will have derived classes like IPhone,AndroidPhone,WindowsMobilePhone can be even
  • Java date parsing without separators?
  • how to map an array of custom type from postgres to java using hibernate
  • Why hibernate always call "update" statement after using "select" statement in MySQL?
  • An interview topic: What can go wrong with this code?
  • How do I regex remove whitespace and newlines from a text, except for when they are in a json's string?
  • How to turn off Preferences > Compiles > User External Build?
  • how to convert arraylist to string array with all items in double quote
  • PMD+Maven+JAVA Error:: Can't find resource rulesets/comments.xml. Make sure the resource is a valid file or URL or is on
  • How to extend AbstractScheduledService.Scheduler
  • Primefaces tabview: set Active Index after some counting
  • Need help in Regex to exclude splitting string within "
  • Get header from HttpUrlConnection object
  • encoding xlsx as base64 and send it as an attachment
  • How to acess HttpServletRequest in Jaas login module in Tomcat
  • How to implement a basic pointer
  • Java Swing Exit Icon?
  • Why onNext has no effect
  • IntelliJ Idea 2018.2 no option for importing gradle project
  • Remove a negative element from an array w/o array.copy
  • Could this prevent overflow in Java?
  • In Java Swing, can I receive Caret events in real time?
  • I need help not using brute force when using JFrames and DrawWindows
  • How do I refactor ArrayList<MyClass> into MyClassLIst?
  • My program keeps saying that the method cannot be resolved
  • BubbleSort -my code returns random addresses
  • JavaFX components inside HTML?
  • Character in Java game not responding
  • Working around access denied in a FileWalking Tree in Java7
  • How to avoid if/else when using multple suppliers?
  • How to pass object from table cell editor to Table Model?
  • Paypal Sandbox payment state pending
  • sejda-console.bat passing parameters with spaces
  • Multiple Consumers Spring Kafka
  • Bitbucket pipeline: environmental variables in build.gradle file not recognized
  • Java static enum method to return a default enum value
  • What is the complexity of empty for loop?
  • Group randomly List of Lists as N subsets with K elements in each
  • How to set texture on a shape drawn by glDrawArrays()?
  • How to make a jlabel resizable according to the window
  • Java Mathematical Expression Syntax
  • assigning values to characters in java
  • Method overriding and Inheritance in java
  • given a set of lists/groups with a series of number, find matching numbers
  • Connection to HID USB device (keyboard and mouse) in android
  • Inject HttpServletRequest in CDI SessionScoped bean
  • Pool game in java - ball collision algorithm
  • Focus ScrollView to selected position programmatically - Android
  • Is it hibernate bug?
  • Glib memory allocation error
  • Android Proguard - step by step
  • Setting the pivot point of a JPanel to its center
  • java check time is greater time
  • how to save a screenshot (matlab)
  • Anti-aliasing filled shapes in libgdx
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org